typescript 散列变量语法在打字稿中是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21070401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does the hash variable syntax work in typescript?
提问by Doug
...and where is it documented?
......它在哪里记录?
I've seen examples like this around the place:
我在这个地方看到过这样的例子:
class MyThing {
private _layers: { [id: string] : SimpleLayer } = {};
...
}
...and that works, which is great, but the syntax is confusing to me.
...这是有效的,这很棒,但语法让我感到困惑。
What is 'id'? Why is the syntax not just blah:{string:SimpleLayer}, which doesnt work. I've also seen {[name: string]:Type} and {[index:string]:Type}.
什么是“身”?为什么语法不只是 blah:{string:SimpleLayer},它不起作用。我还看到了 {[name: string]:Type} 和 {[index:string]:Type}。
I've been looking over typescriptlang.org trying to find where this is actually documented, but I can't seem to find it at all.
我一直在查看 typescriptlang.org 试图找到实际记录的位置,但我似乎根本找不到它。
回答by JLRishe
TypeScript Walkthrough: Interfaces
See the section "Describing an Indexable Object". This is called an index signature.
请参阅“描述可索引对象”一节。这称为索引签名。
The syntax for defining the index is:
定义索引的语法是:
[Identifier: KeyType]: ValueType
KeyType
can be either string
or number
.
KeyType
可以是string
或number
。
You could claim that the Identifier
isn't really needed since it doesn't get used anywhere, but I think it's required in order to force the class/interface designer to indicate what the hash map key should represent (an id, name, e-mail address, etc.). This also provides the possibility of having intellisense show the hash key name (as Visual Studio does for other languages), though I don't think Typescript intellisense currently provides this.
您可以声称它Identifier
并不是真正需要的,因为它不会在任何地方使用,但我认为这是强制类/接口设计器指示哈希映射键应表示的内容(id、名称、e-邮件地址等)。这也提供了让智能感知显示哈希键名称的可能性(就像 Visual Studio 对其他语言所做的那样),尽管我认为 Typescript 智能感知目前没有提供这一点。
回答by meagar
Regarding your question of why the syntax isn't simpler, specifically something like blah:{string:SimpleLayer}
:
关于你为什么语法不简单的问题,特别是这样的blah:{string:SimpleLayer}
:
Because this would be ambiguous. This syntax already exists and has meaning:
因为这将是模棱两可的。此语法已存在并具有以下含义:
var x: { string: SimpleLayer }
This declares a variable x
. The type of x
has one property, named string
, which is of type SimpleLayer
. If I wanted to use x
, I would do this:
这声明了一个变量x
。的类型x
有一个名为 的属性string
,它的类型为SimpleLayer
。如果我想使用x
,我会这样做:
x.string = new SimpleLayer;
It's more obvious if we use a real example:
如果我们使用一个真实的例子就更明显了:
var circle: {radius: number}
This declares a variable with one property (radius
) that is of type number
, it does notdeclare a hash mapping radius
types to number
types.
这声明了一个具有一个属性 ( radius
)的变量number
,它是 type ,它没有声明radius
类型到number
类型的哈希映射。