Skip to content

Inferring type from Record where keys are template literal types should return correct value typeΒ #42159

Closed
@minheq

Description

@minheq

Bug Report

πŸ”Ž Search Terms

  • record template literal types [infer]
  • record template literal key
  • template literal types

Found #29718 but not sure if it is the same error

πŸ•— Version & Regression Information

TypeScript v4.2.0-dev.20201230

⏯ Playground Link

https://www.typescriptlang.org/play?ts=4.2.0-dev.20201230#code/PTAEBcE8AcFNQMIHsA2SBOoC8oDO50BLAOwHNQRQAVAC0N1AHcMBrXAKCjkVQ21AAGAY17oAJAG98RMgF8BnGPGRp0DHACVYI9ABMAPCowAaPARKkAfAG527EcXygRq3AC4er-hPag-oAHIXDAAhFABXWACPALDIgONff0oAZRokcJRdUGh0JABbaHBQWHQ89AB+JL8AkgA3AEMUQl1owK1WxNk7ShCAVQBxADpnUVASADNShnAkQXDiFiRGYgFxx3BYBuykCcFpCwEh+yQN0dV+UlhwAGlYSAA1JsiACmC1UyDROKiASjsJgshOBCKdQFdbvcnhFYPoklQSgAPTbEXQMLQ6AwHMimBYsYjLYiWRJ+G5IlFo0Ase67ajsSwvJAAIwAVh4qKZqZAPDdfuyANo3AC6oB8fnQ13C6GIoGZLP5XKFtm6QA

πŸ’» Code

// type Color = string // This works
type Color = `color${string}`
type Colors = Record<Color, string>;

const colors: Colors = {
    'colorBlue': 'Blue',
    // BUG. should prompt error?
    'invalid': 'Red',
}

// BUG. color infers to `unkown` instead of `string`.
const color = getKeyValue(colors, 'colorBlue')

function getKeyValue<
  T extends Record<string, unknown>,
  K extends keyof T
>(obj: T, key: K): T[K] {
  return obj[key];
}

πŸ™ Actual behavior

  • getKeyValue(colors, 'colorBlue') infers unknown
  • 'invalid': 'Red', is still valid key for colors: Colors

πŸ™‚ Expected behavior

  • getKeyValue(colors, 'colorBlue') should infer string return value
  • 'invalid': 'Red', should prompt an error as it does not match template literal type

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions