microsoft / microsoft/TypeScript
Type inference with conditional for array fails for literal
Open
Nobody has claimed this yet.
Needs Investigation
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 3.9.2
Search Terms: typescript infer array type conditional literal
Code
function func<T>(opt: {
value: T;
arrayValue: T extends any[] ? T : T[];
}) {}
func({
value: [1, 2, 3],
arrayValue: [1, 2, 3],
}); // throws error
const obj = {
value: [1, 2, 3],
arrayValue: [1, 2, 3],
};
func(obj);
Expected behavior:
No error is thrown.
Actual behavior:
The commented function call throws the following error:
Type 'number[]' is not assignable to type 'number'.(2322)
input.ts(2, 3): The expected type comes from property 'value' which is declared here on type '{ value: number; arrayValue: number[]; }'
Related Issues:
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 by reproducing the generic conditional-type example in the linked TypeScript Playground and compare the direct call with the call using obj. Trace the type inference and conditional-type handling involved; done means the direct call produces no error while preserving the expected inferred array types, with a regression test for the example.
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