Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple with fixed length

Typescript in tuple allows to add extra elements with any of types used before, but I would like to limit the length. I've tried with & { length: 2 }, but it didn't helped:

declare var a: [string, number] & { length: 2 };

a[0] = "1"
a[1] = 2;
a[2] = "3";
a[3] = 4;

Assignments for [2] and [3] don't produce error. How can I specify corresponding type?

like image 528
Qwertiy Avatar asked Sep 24 '18 18:09

Qwertiy


1 Answers

Use type never for array tail:

declare var a: [string, number, ...never[]];

and you'll get

Type '"3"' is not assignable to type 'never'.

Type '4' is not assignable to type 'never'.

like image 133
Qwertiy Avatar answered Sep 20 '22 09:09

Qwertiy