简体   繁体   English

TypeScript keyof和Indexer兼容性?

[英]TypeScript keyof and Indexer compatibility?

I have a method signature which expect a second argument of keyof Array<...> . 我有一个方法签名,期望keyof Array<...>的第二个参数。 Since Array interface defines an indexer [n: number]: T; 由于Array接口定义了一个索引器[n: number]: T; I'd expect to be some way to refer to some index in the method. 我期望在某种程度上引用方法中的某个索引。

But I can't find how. 但我找不到怎么样。 I tried the following: 我尝试了以下方法:

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 ...

And none is working. 没有人工作。

You could always try: 你总是可以尝试:

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

keyof Array<...> refers to all property names of arrays, like length , toString , push , pop , etc. Number indices aren't part of the Array interface in the same manner because they're a lookup type : keyof Array<...>是指数组的所有属性名称,如lengthtoStringpushpop等。数字索引不是同一种方式的Array接口的一部分,因为它们是查找类型

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

   ... etc ...

  [n: number]: T;
}

Consider a simpler interface: 考虑一个更简单的接口:

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

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

This is actually a shortcoming of the language. 这实际上是语言的缺点。 See also this issue on GitHub : 另请参阅GitHub上的此问题

We can not list all these numeric string literals (effectively). 我们无法列出所有这些数字字符串文字(有效)。 keyof Container<T> would be number | numericString keyof Container<T>将是number | numericString number | numericString with numericString as type of all numeric string literals with a corresponding number literal. number | numericString with numericString作为所有数字字符串文字的类型,具有相应的数字文字。 number | string number | string wouldn't be correct because not every string is a numericString . number | string不正确,因为并非每个string都是numericString Also not every string sequence of digit characters is a numbericString since number has a maximum and minimum value. 并非每个数字字符串序列都是numbericString因为number具有最大值和最小值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM