microsoft / microsoft/TypeScript
Fail to infer Indexed access to the intersection type when it includes an union derived from a generic input
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
🔎 Search Terms
"indexed access on union", "generic index"
🕗 Version & Regression Information
5.6.2, and it seems never worked for every ts versions.
⏯ Playground Link
💻 Code
type Test<T extends string> = {[K in T]: {key: K}}[T] & {target: string}
const foo = <T extends string>(arg: Test<T>) => {
const value: Test<T> = arg;
const value2: Test<T>['key'] = arg['key'];
const value3: Test<T>['target'] = arg['target']; // Error
}
🙁 Actual behavior
The declaration of value and value2 works well, but ts emit an error saying Type 'string' is not assignable to type '{ [K in T]: { key: K; }; }[T]["target"] & string' for value3.
🙂 Expected behavior
The Test<T>['target'] should equal to string and assume the type of '{ [K in T]: { key: K; }; }[T]["target"] as any before intersection, as it does when I give non-generic type in the same place. It seems even weird because it well infers the type of Test<T>['key'].
Additional information about the issue
With additional experiment, I found that it always happens when I generate an union type with generic input. For instance,
type Test<T> = (T extends string ? {key: number} : {key: string}) & {target: string}
const foo = <T extends string>(arg: Test<T>) => {
const value: Test<T> = arg;
const value2: Test<T>['key'] = arg['key'];
const value3: Test<T>['target'] = arg['target']; // Error
}
it also does not work in the case above
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground reproduction and compare the generic and non-generic indexed-access cases shown in the issue. Done means the generic indexed access for the intersection type accepts the string value for the target property without producing the reported type error, while the existing key inference remains correct.
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
- 35/100