TypeScript Version: every version tested (from 2.3.0 to 2.5.0-dev.20170613)
Code
type Tuple = [number, number];
let t1: Tuple = [1, 2];
let t2: Tuple = t1.slice();
let t3: Tuple = t1.slice(0);
let t4: Tuple = [...t1];
Expected behavior:
No error
Actual behavior:
test-slice.ts(3,5): error TS2322: Type 'number[]' is not assignable to type '[number, number]'.
Property '0' is missing in type 'number[]'.
test-slice.ts(4,5): error TS2322: Type 'number[]' is not assignable to type '[number, number]'.
test-slice.ts(5,5): error TS2322: Type 'number[]' is not assignable to type '[number, number]'.
array.slice() and array.slice(0) and [...array] are common idiomatic ways to shallow-clone an array. Unfortunately, this loses the tuple type information.
I don't know how easy this would be to fix, but even something like supporting only tuples below a certain length (by hardcoding [T1, T2] => [T1, T2] type signatures for Array#slice) would be a pretty big improvement for my own use-case.
I suppose we can make Tuple extend from a new Tuple interface instead of Array, and make that return this in a punch of places.
For some reason #4988 was closed but this was left open. I just want one correct, non-verbose way to clone a tuple.
I don't remember exactly what led me to post this a few months ago but as of now it looks like slice does return the same tuple. Unfortunately, so does slice(0,1) so you can easily give yourself a tuple that's actually shorter than should be guaranteed. Is that intentional?
Most helpful comment
I suppose we can make Tuple extend from a new
Tupleinterface instead ofArray, and make that returnthisin a punch of places.