-
Notifications
You must be signed in to change notification settings - Fork 13k
Description
🔎 Search Terms
Array.from is currently declared as
from<T>(iterable: Iterable<T> | ArrayLike<T>): T[];
This means that unions of distinct iterable types cannot be turned into arrays of the same type.
let foo: Iterable<string> | Iterable<number> = /* ... */;
let q: Array<string> | Array<number> = Array.from(foo); // Fails type checking, cannot find overload (2769)
The array splat operator has a different problem: it tries to create an array that is a union of both types.
let foo: Iterable<string> | Iterable<number> = /* ... */;
let q: Array<string> | Array<number> = [...foo]; // Fails type checking, not assignable to type (2322)
My instinct is that there should be some way to use variadic types here, but tbh I don't really know how.
Does this need new syntax? Or does it work within the existing type system?
🕗 Version & Regression Information
Since at least 4.0; prior to 4.0 it still fails but Array.from did not support taking an Iterable.
Still around in 6.0.0-dev.20251009
⏯ Playground Link
💻 Code
type Foo = Iterable<string> | Iterable<number>;
function tryArrayFrom(foo: Foo) {
let q: Array<string> | Array<number> = Array.from(foo);
}
function trySplat(foo: Foo) {
let q: Array<string> | Array<number> = [...foo];
}
🙁 Actual behavior
for tryArrayFrom
No overload matches this call.
Overload 1 of 4, '(iterable: Iterable | ArrayLike): string[]', gave the following error.
Argument of type 'Foo' is not assignable to parameter of type 'Iterable | ArrayLike'.
Type 'Iterable' is not assignable to type 'Iterable | ArrayLike'.
Type 'Iterable' is not assignable to type 'Iterable'.
The types returned by 'Symbol.iterator.next(...)' are incompatible between these types.
Type 'IteratorResult<number, any>' is not assignable to type 'IteratorResult<string, any>'.
Type 'IteratorYieldResult' is not assignable to type 'IteratorResult<string, any>'.
Type 'IteratorYieldResult' is not assignable to type 'IteratorYieldResult'.
Type 'number' is not assignable to type 'string'.
Overload 2 of 4, '(arrayLike: ArrayLike<string | number>): (string | number)[]', gave the following error.
Argument of type 'Foo' is not assignable to parameter of type 'ArrayLike<string | number>'.
Property 'length' is missing in type 'Iterable' but required in type 'ArrayLike<string | number>'.
for trySplat
Type '(string | number)[]' is not assignable to type 'string[] | number[]'.
Type '(string | number)[]' is not assignable to type 'string[]'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
🙂 Expected behavior
Array.from a union of Iterables should return a union of Arrays.
Additional information about the issue
No response