microsoft / microsoft/TypeScript
Assigning array values by index treats Array<A> | Array<B> as Array<A | B>
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 4.0.0-dev.201xxxxx
reproducible starting from at least 3.3.3
Search Terms: discriminated unions, distributive
Code
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
function main() {
var a: (number[] | string[]) = [];
a[0] = 3;
a[1] = "xxx";
}
Expected behavior:
error TS2322: Type '"xxx"' is not assignable to type 'number'.
Actual behavior:
All is compiled without warnings or errors.
Keep in mind that this works as expected:
var a: (number[] | string[]) = [3, "xxx"]; // Not OK as it should be
Thus, depending on how exactly we're initialising the array, behaviour differs.
Playground Link:
https://www.typescriptlang.org/play?ts=4.0.0-dev.20200508#code/C4TwDgpgBAggTnAcgVwLYGVhygXigOzQCMI4BtAXSgB8oBnLAS3wHNKBuAKE4DNl8AxsEYB7fFFQBDZgAoAlFADenKKqgA3SdkkAuKDMKoS5KrQZxmbCgtxQOUFWslkADFTwBmLmqjOAjO5QAEQAHmFBXAC+nEA
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 with the self-contained TypeScript reproducer and run it through the command-line tsc, comparing indexed assignments with array-literal initialization. The issue names no source files or tests, so trace the checker path for indexed assignment on a union of array types. Done means the reproduced assignment reports the expected type error without regressing the related initialization behavior.
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
- Clearly specified
- Newbie friendliness
- 35/100