Ahmed Sbai
Ahmed Sbai

Reputation: 16199

Push inside Tuple TypeScript

I am learning TypeScript especially the tuple type. According to docs this is the definition of tuple :

A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.

I tried this :

let test : [string,number] ;
test = ['a',2];
console.log(test); // output ["a", 2] 

Now when I try to assign an invalid value to the test variable :

test = ['a',2,5] // Error : Type '[string, number, number]' is not assignable to type '[string, number]'.

However when I try tp push inside test the compiler does not complain

test.push(5) // NO ERROS
console.log(test) // output ["a", 2, 5] 

How this can be possible ?

Upvotes: 0

Views: 73

Answers (1)

jsejcksn
jsejcksn

Reputation: 33739

This is a limitation of the current design of TypeScript and has been reported at this GitHub issue:

microsoft/TypeScript#52375 - Bug: incorrect tuple (array) type after changing in place

The current development lead of TS posted this comment about it:

RyanCavanaugh:

The in-place mutation methods for arrays aren't supported from a control flow perspective. I recommend using readonly [string, number] in most scenarios.

and also suggested this:

RyanCavanaugh:

[X] and readonly [X] seem to cover the use cases fairly well. I would probably suggest

type StrictTuple<T> = Omit<T, "push" | "pop" | "shift" | "unshift" | "sort">;

since things like indexOf, map, every, etc are still presumably useful.

Upvotes: 2

Related Questions