microsoft / microsoft/TypeScript
Type inference in index type assignment is skipped
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 3.8.3
Search Terms: index indexed type assignment initialize initializer initialization inference object narrow narrowing assertion
Code
type One = { name: string; };
type Many = Array<One>;
type OneOrMany = One | Many;
var one: OneOrMany = { name: "sam" };
one.name = "pat"
var many: OneOrMany = [{ name: "sam" },{ name: "ash" }];
many[0].name = "pat"
// all is well here
interface OOMDict { [key: string]: OneOrMany; }
var oomdict2: OOMDict = {};
oomdict2.one = { name: "sam" };
oomdict2.one.name = "pat";
oomdict2.many = [{ name: "sam" }, { name: "ash" }];
oomdict2.many[0].name = "pat";
// all is well here
// testing resolution within an index type initializer
var oomdict: OOMDict = { one: { name: "sam" }, many: [{ name: "sam" }, { name: "ash" }] };
oomdict.one.name = "pat";
// ERROR: Property 'name' does not exist on type 'OneOrMany'.
// ERROR: Property 'name' does not exist on type 'Many'.(2339)
oomdict.many[0].name = "pat";
// ERROR: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'OneOrMany'.
// ERROR: Property '0' does not exist on type 'OneOrMany'.(7053)
Expected behavior: Initialization / assignment of an OOMDict object effects type inference on its OneOrMany values identically to initialization or assignment of a OneOrMany variable.
Actual behavior: Values in an OOMDict either do not narrow based on their contents and type inference (oomdict.many does not narrow from OneOrMany to Many) or they narrow to the wrong specific type (oomdict.one narrows from OneOfMany to Many instead of One).
Related Issues: https://github.com/Microsoft/TypeScript/issues/1706 https://github.com/microsoft/TypeScript/issues/5089
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 minimal reproduction in the issue or its Playground link, using the TypeScript 3.8.3 behavior as the baseline. Compare narrowing for direct OneOrMany initialization with values inside the OOMDict index-type initializer. Done means the two OOMDict property assignments narrow like the direct assignments and no reported type errors remain.
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