Reputation: 3014
According to the documentation, accessing indices beyond the size of the tuple yields a union type of all known types in the tuple, rather than undefined or outright throwing an error.
Is it currently possible to make this an error?
Upvotes: 0
Views: 54
Reputation: 328302
No. As @AsadSaeeduddin says, this request is tracked in Microsoft/TypeScript#6229.
If you really want them, you can define your own "closed" tuples:
interface Closed1<T> { 0: T }
interface Closed2<T, U> extends Closed1<T> { 1: U }
interface Closed3<T, U, V> extends Closed2<T, U> { 2: V }
interface Closed4<T, U, V, W> extends Closed3<T, U, V> { 3: W }
// as many as you like ...
function closeTuple<T, U, V, W>(open: [T, U, V, W]): Closed4<T, U, V, W>;
function closeTuple<T, U, V>(open: [T, U, V]): Closed3<T, U, V>;
function closeTuple<T, U>(open: [T, U]): Closed2<T, U>;
function closeTuple<T>(open: [T]): Closed1<T>;
function closeTuple(open: any): any {
return open;
}
function openTuple<T, U, V, W>(closed: Closed4<T, U, V, W>): [T, U, V, W];
function openTuple<T, U, V>(closed: Closed3<T, U, V>): [T, U, V];
function openTuple<T, U>(closed: Closed2<T, U>): [T, U];
function openTuple<T>(closed: Closed1<1>): [T];
function openTuple(closed: any): any {
return closed;
}
// demo usage
const anOpenTuple: [string, boolean, number] = ['foo', true, 2];
const okay = anOpenTuple[2]; // number
const what = anOpenTuple[10]; // string | number | boolean
const aClosedTuple = closeTuple(anOpenTuple);
const stillOkay = aClosedTuple[2]; // number
const nowError = aClosedTuple[10]; // error if you have noImplicitAny on
Then you can convert between open and closed tuples when you need to. However, once you start down this path, you will probably find it's better to just create interfaces with specific named properties instead of relying on tuples at all. But your mileage may vary.
Hope that helps; good luck.
Upvotes: 1