microsoft / microsoft/TypeScript

Assigning array values by index treats Array<A> | Array<B> as Array<A | B>

Open
#38,445 8 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.