Skip to content

Inconsistent generic type inference between record type and object literal type #56821

Description

@hkleungai

🔎 Search Terms

record, generics, object literal

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Generics

⏯ Playground Link

https://tsplay.dev/mq0kQN

💻 Code

declare function forEach<T extends string | number | symbol>(
    data: { [a in T]: unknown },
    cb: (x: T) => unknown
): void;

declare let record: Record<string, unknown>;
forEach(record, key => {})
//              ^?

declare let obj: { [a: string]: unknown };
forEach(obj,    key => {})
//              ^?

🙁 Actual behavior

  • key for record: Record<string, unknown> is inferred as string type
  • key for { [a: string]: unknown } is inferred as string | number type

🙂 Expected behavior

both key should be inferred as the same type, i.e. string type.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions