TypeScript keyof和Indexer兼容性?

我有一个方法签名,期望keyof Array< …>的第二个参数.

由于Array接口定义了一个索引器[n:number]:T;我期望在某种程度上引用方法中的某个索引.

但我找不到怎么样.
我尝试了以下方法:

MyMethod(myArray, 0); // Argument of type '0' is not assignable to parameter of type ...
MyMethod(myArray, [0]); // Argument of type 'number[]' is not assignable to parameter of type ...
MyMethod(myArray, '0'); // Argument of type '"0"' is not assignable to parameter of type ...
MyMethod(myArray, '[0]'); //  Argument of type '"[0]"' is not assignable to parameter of type ...

没有人工作.

最佳答案 你总是可以尝试:

function myFun<T>(arr: Array<T>, index: number) {
  return arr[index];
}

keyof Array< …>指的是数组的所有属性名称,如length,toString,push,pop等.数字索引不是同一种方式的Array接口的一部分,因为它们是lookup type:

interface Array<T> {
  length: number;
  toString(): string;

   ... etc ...

  [n: number]: T;
}

考虑一个更简单的接口:

interface Arr<T> {
  [n: number]: T;
}

const variable: keyof Arr<number>; // variable is of type "never"

这实际上是语言的缺点.另见this issue on GitHub:

We can not list all these numeric string literals (effectively). keyof Container<T> would be number | numericString with numericString as type of all numeric string literals with a corresponding number literal. number | string wouldn’t be correct because not every string is a numericString. Also not every string sequence of digit characters is a numbericString since number has a maximum and minimum value.

点赞