简体   繁体   中英

Array destructuring incorrectly infers the type of created array

If we have an object typed as a union of two arrays of different types:

const original = [] as string[] | number[];

After the destructuring assignment the type changes to array of union of said types:

const copy = [...original]; // (string | number)[];

Which widened the type for no reason.

And what's worse, Array.from doesn't even work:

const copyFrom = Array.from(original);
// Type 'number' is not assignable to type 'string'. 

But it does with explicit typing:

const copyExplicit = Array.from<string | number>(arr);

Typescript version is 3.7.3

If you want to copy array without loosing type, just use slice

const copy = original.slice();

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM