可索引类型-TypeScript [英] Indexable type - TypeScript
问题描述
语法如下,
interface StringArray {
[index: number]: string;
}
指出,当用number
索引StringArray
时,它将返回string
.例如-let myArray: StringArray;myArray = ["Bob", "Fred"];let myStr: string = myArray[0];
states that when a StringArray
is indexed with a number
, it will return a string
. For example - let myArray: StringArray;myArray = ["Bob", "Fred"];let myStr: string = myArray[0];
因此,通过将myArray
声明为StringArray
类型,将myArray
的类型限制为存储为string
类型的值.尽管键(index)被称为number
So, myArray
is type constrained on values stored as string
type, by declaring it with type StringArray
. Key(index) is always string
type, under the hood(JavaScript), despite mentioning it as number
根据以下语法,
class Animal{
name: string;
}
class Dog extends Animal{
breed: string;
}
interface NotOkay {
[x: number]: Animal;
[x: string]: Dog;
}
1)NotOkay
语法说明什么?
根据以下语法,
interface NumberDictionary {
[index: string]: number;
length: number; // ok, length is a number
name: string; // error, the type of 'name' is not a subtype of the indexer
}
2)NumberDictionary
表示什么?
3)为什么这两种语法是错误的? error TS2413
& error: TS2411
3) Why these two syntax are wrong? error TS2413
& error: TS2411
推荐答案
(as @betadeveloper points out, the examples are taken from the typescript documentation at https://www.typescriptlang.org/docs/handbook/interfaces.html)
1 + 3)文档指出的一点是此声明不一致.
1+3) The point the documentation is making is that this declaration is not consistent.
该声明似乎表明此代码有效:
The declaration would seem to say that this code works:
let no: NotOkay
function byString(key: string): Dog {
return no[key]
}
function byNumber(key: number): Animal {
return no[key]
}
但是问题是,例如no[0]
的确与no['0']
相同(这就是JavaScript的工作方式).因此,byString('0')
实际上会 只会产生动物,而不一定是狗.
But the problem is that a lookup of e.g. no[0]
is really the same things as no['0']
(it's how JavaScript works). So byString('0')
will actually just result in an Animal, not necessarily a Dog.
因此,为防止上述代码-看起来正确,但实际上对于某些字符串键(那些恰好是字符串形式的数字)是错误的-TypeScript不允许声明.
So to prevent the code above – that looks correct but is in fact wrong for certain string keys (those that happen to be numbers in string form) – TypeScript does not allow the declaration.
2 + 3)[index: string]: number;
表示您可以将任何字符串用作NumberDictionary
的索引,并且您会得到一个数字.
2+3) [index: string]: number;
says that you can use any string as an index of a NumberDictionary
and you will get a number.
另一方面,name: string;
表示属性name
是字符串.但是属性也可以作为索引访问,例如做的时候
On the other hand, name: string;
says that the property name
is a string. But a property can also be accessed as an index, so e.g. when doing
let nd: NumberDictionary
let a = nd['name']
let b = nd.name
a和b表示完全相同,但是第一个声明似乎说a
是一个数字,而第二个声明似乎说b
是一个字符串.这是矛盾的,因此也不允许此声明.
a and b mean exactly the same thing, but the first declaration seemed to say a
was a number, whereas the second declaration seems to say b
is a string. That's a contradiction and therefore this declaration is also not allowed.
这篇关于可索引类型-TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!