Skip to content

"keyof" infers type incorrectly when it is applied to interface that extends Record<string, any> #55706

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
nicky1038 opened this issue Sep 11, 2023 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@nicky1038
Copy link

nicky1038 commented Sep 11, 2023

πŸ”Ž Search Terms

keyof interface extends record number

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

Link

πŸ’» Code

interface EmptyInterface {};
type StringRecord = Record<string, string>;
interface Interface extends StringRecord {};

type EIFKey = keyof EmptyInterface // never
type SRKey = keyof StringRecord // string
type IFKey = keyof Interface // number | string, why not string?

πŸ™ Actual behavior

IFKey is number | string

πŸ™‚ Expected behavior

IFKey should be string

@nicky1038 nicky1038 changed the title keyof interface is inferred incorrectly when interface extends Record<string, any> keyof infers type incorrectly when it is applied to interface that extends Record<string, any> Sep 11, 2023
@nicky1038 nicky1038 changed the title keyof infers type incorrectly when it is applied to interface that extends Record<string, any> "keyof" infers type incorrectly when it is applied to interface that extends Record<string, any> Sep 11, 2023
@Andarist
Copy link
Contributor

In general, what is indexable by string is also indexable by number:

const stringRecord: StringRecord = {};
const test1 = stringRecord["foo"];
const test2 = stringRecord[100];

const interface_: Interface = {};
const test3 = interface_["foo"];
const test4 = interface_[100];

The difference in keyof results here is surprising to me though.

@fatcerberus
Copy link

I believe the difference in behavior comes down to, Record is implemented as a mapped type. keyof MappedTypeOverString is string. Interfaces can’t be mapped types though (AFAIK), so extending a Record<string, T> demotes it to an index signature, and keyof StringIndexSignatureType is string | number, by design.

@andrewbranch andrewbranch added the Question An issue which isn't directly actionable in code label Sep 11, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Question" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

5 participants