Assigning array values by index treats Array<A> | Array<B> as Array<A | B>
See original GitHub issueTypeScript 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:
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:8 (4 by maintainers)
Top Results From Across the Web
Arrays and References | Think Java | Trinket
As explained in Section 7.2, array variables contain references to arrays. ... If we find the target value in the array, we return...
Read more >Array - JavaScript - MDN Web Docs
JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes,ย ...
Read more >5. Working with Arrays and Loops - JavaScript Cookbook [Book]
You want to filter element values in an array and assign the results to a new array. Solution. Use the Array object filter...
Read more >Arrays
Two arrays of size 10, both with indices 0 .. 9 ... Same syntax as a function call (both take and return a...
Read more >AWK Language Programming - Arrays in awk - Math
An array is a table of values, called elements. The elements of an array are distinguished by their indices. Indices may be either...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I would personally expect TypeScript to error on me if I ever tried to assign a value to a union of arrays where the value being assigned was not compatible with all arrays in the union.
A similar concern arises with discriminated unions