Skip to content

The Keyof Type Operator shows inconsistent behavior. #56938

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
13OnTheCode opened this issue Jan 3, 2024 · 2 comments
Closed

The Keyof Type Operator shows inconsistent behavior. #56938

13OnTheCode opened this issue Jan 3, 2024 · 2 comments
Labels
Not a Defect This behavior is one of several equally-correct options

Comments

@13OnTheCode
Copy link

13OnTheCode commented Jan 3, 2024

πŸ”Ž Search Terms

The Keyof Type Operator shows inconsistent behavior.

πŸ•— Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play?#code/C4TwDgpgBAKgjFAvFA3lA2gDwFxQM7ABOAlgHYDmAurgK6kDWpA9gO6lQC+AsAFAD0fKEIB6Afl69QkKACUEyehBBMAZrDi8BQqGIk8p0GACYksiAGMmhACYAeAiQoAaKHUatSAPk2CR4npLg0DImCkqqsEY+2ro8QA

πŸ’» Code

type T1 = { [x: string]: unknown }
//   ^? type T1 = { [x: string]: unknown; }

type R1 = keyof T1
//   ^? type R1 = string | number

type T2 = Record<string, unknown>
//   ^? type T2 = { [x: string]: unknown; }

type R2 = keyof T2
//   ^? type R2 = string

πŸ™ Actual behavior

According to the type hint, the types of T1 and T2 are the same, but the results they get through keyof are not the same. According to the document, they should both get string | number .

Document link: https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content

πŸ™‚ Expected behavior

Infer the correct type.

Additional information about the issue

In addition, it may also be related to #56888.

@MartinJohns
Copy link
Contributor

MartinJohns commented Jan 3, 2024

This is working as intended, see also #55706. Duplicate of #49540.

Record<> is implemented as a mapped type, it behaves different than an indexed type.

Used search terms: keyof record in:title

@fatcerberus
Copy link

Yeah, it's confusing that Record<string, T> is displayed as an index-signature type in type hints. It's actually a mapped type over string, which, while they behave similarly most of the time, is not the same thing as a string index signature.

@RyanCavanaugh RyanCavanaugh added the Not a Defect This behavior is one of several equally-correct options label Jan 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Not a Defect This behavior is one of several equally-correct options
Projects
None yet
Development

No branches or pull requests

4 participants