Typescript: Cloning a tuple turns it into an array

Created on 13 Jun 2017  路  3Comments  路  Source: microsoft/TypeScript

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.

In Discussion Suggestion

Most helpful comment

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.

All 3 comments

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?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DanielRosenwasser picture DanielRosenwasser  路  3Comments

seanzer picture seanzer  路  3Comments

blendsdk picture blendsdk  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

dlaberge picture dlaberge  路  3Comments