Closed
Description
TypeScript Version: 3.3.0-dev.20190108
Search Terms: spread, rest, type conversion, tuple, array length
Code
type test1 = [...number[]] // number[] <-- Is it a feature?
type test2 = [number, ...number[]] // [number, ...number[]]
type test3 = [number?, ...number[]] // [number?, ...number[]]
type fixed1 = test1 & { length: 2 } // number[] & { length: 2 }
type fixed2 = test2 & { length: 2 } // [number, ...number[]] & { length: 2 }
type fixed3 = test3 & { length: 2 } // [number?, ...number[]] & { length: 2 }
let var1: fixed1 = [0, 0]
/* error TS2322: Type 'number[]' is not assignable to type 'fixed1'.
Type 'number[]' is not assignable to type '{ length: 2; }'.
Types of property 'length' are incompatible.
Type 'number' is not assignable to type '2'. */
let var2: fixed2 = [0, 0] // OK
let var3: fixed3 = [0, 0] // OK
Expected behaviour:
Expected [...number[]]
and [number, ...number[]]
to have the same behaviour except that the latter requires at least one element in tuple.
Actual behavior:
[...number[]]
is implicitly converted to number[]
with the length: number
field, that is incompatible with length: 2
Error TS2322: Type 'number[]' is not assignable to type 'fixed1'.
Type 'number[]' is not assignable to type '{ length: 2; }'.
Types of property 'length' are incompatible.
Type 'number' is not assignable to type '2'.
Playground Link: 🔗
Related Issues: Haven't found anything about the same problem.