microsoft / microsoft/TypeScript

keyof on generics arbitrarily returns `string` rather than the inferred values depending on the generic

Open
#44,121 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: Index Types
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Bug Report

🔎 Search Terms

keyof generic string

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about it
⏯ Playground Link

Playground link with relevant code

💻 Code
export type Item = {
  args?: Record<string, string>;
};

export type BaseSpec = Record<string, {
  items: Item[];
}>;

export function genericFunction<Spec extends BaseSpec>(spec: Spec): keyof Spec {
  return {} as any;
}

const AAAAA: `someKey` = genericFunction({
  someKey: {
    items: [{
      args: {},
    }, {
      args: {
        name: `foo`,
      },
    }],
  },
});
🙁 Actual behavior
Type 'string' is not assignable to type '"someKey"'.
🙂 Expected behavior

No errors

💻 Additional Information

Weirdly, it seems to work if all args objects that are specified have exactly the same content. Removing an arg object seems to work, and it works as well if we add name: "foo" into the first arg object (or remove it from the second one).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Open the linked TypeScript Playground and reproduce the error with genericFunction, BaseSpec, and the differing args objects. Investigate why keyof Spec is widened to string in this generic inference case, then verify that the example type-checks and that the inferred result is "someKey".

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.