散列变量语法在打字稿中是如何工作的? [英] How does the hash variable syntax work in typescript?

查看:26
本文介绍了散列变量语法在打字稿中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

...它记录在哪里?

我在附近看到过这样的例子:

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.

什么是id"?为什么语法不只是 blah:{string:SimpleLayer},不起作用.我还看到了 {[name: string]:Type} 和 {[index:string]:Type}.

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

我一直在查看 typescriptlang.org 试图找到实际记录的位置,但我似乎根本找不到.

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.

推荐答案

TypeScript 演练:接口

请参阅描述可索引对象"部分.这称为索引签名.

See the section "Describing an Indexable Object". This is called an index signature.

定义索引的语法是:

[Identifier: KeyType]: ValueType

KeyType 可以是 stringnumber.

您可以声称 Identifier 并不是真正需要的,因为它不会在任何地方使用,但我认为这是强制类/接口设计器指示哈希映射的必要条件键应该代表(ID、姓名、电子邮件地址等).这也提供了让智能感知显示哈希键名称的可能性(就像 Visual Studio 为其他语言所做的那样),尽管我认为 Typescript 智能感知目前没有提供这一点.

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.

这篇关于散列变量语法在打字稿中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆