为什么允许访问元组的额外索引?

时间:2017-10-14 22:20:47

标签: typescript

根据the documentation,访问超出元组大小的索引会产生元组中所有已知类型的联合类型,而不是未定义或完全抛出错误。

目前是否可能导致此错误?

1 个答案:

答案 0 :(得分:1)

没有。正如@AsadSaeeduddin所说,这个请求在Microsoft/TypeScript#6229中被跟踪。

如果你真的想要它们,你可以定义自己的"关闭"元组:

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

然后,您可以在需要时在打开和关闭元组之间进行转换。但是,一旦开始这条路径,您可能会发现创建具有特定命名属性的接口而不是完全依赖元组会更好。但你的里程可能会有所不同。

希望有所帮助;祝好运。