-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Inconsistent generic type inference between record type and object literal type #56821
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
Comments
This is intentional, if surprising. Normally |
Edit: Thanks @fatcerberus for the quick response. I think record / mapped types are the way then :) I find that by changing the obj type from index signature to mapped type, it gives the desired type. Playground link: https://tsplay.dev/mb1nBN Code: declare function forEach<T extends string | number | symbol>(
data: { [a in T]: unknown },
cb: (x: T) => unknown
): void;
declare let obj_index_sig: { [s: string]: unknown };
// ^?
forEach(obj_index_sig, key => {})
// ^?
declare let obj_mapped_type: { [s in string]: unknown }
// ^?
forEach(obj_mapped_type, key => {})
// ^? But then, what is the actual difference between On one hand, it seems the mapped type does not just devolve into an index signature, based on how the tsc successfully interpreted the But on the other hand, the ts playground inlay indicates they have the same "shape" (with the only difference in the LHS key, let obj_index_sig: { [s: string]: unknown; }
let obj_mapped_type: { [x: string]: unknown; } How should I understand the difference between If i understand it correctly, mapped type is essentially a record. But then why the ts inlay shows that mapped type and index-signature type are in same shape? let obj_index_sig: { [s: string]: unknown; }
let obj_mapped_type: { [x: string]: unknown; } |
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Uh oh!
There was an error while loading. Please reload this page.
🔎 Search Terms
record, generics, object literal
🕗 Version & Regression Information
⏯ Playground Link
https://tsplay.dev/mq0kQN
💻 Code
🙁 Actual behavior
key
forrecord: Record<string, unknown>
is inferred asstring
typekey
for{ [a: string]: unknown }
is inferred asstring | number
type🙂 Expected behavior
both
key
should be inferred as the same type, i.e.string
type.Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: