简体   繁体   English

请解释? 打字稿索引签名

[英]Please explain? Typescript index signature

I've just stumbled across the following syntax in TypeScript 我刚刚在TypeScript中偶然发现了以下语法

export interface OrderPool {
    [id: string]: Level3Order;
}

Could someone clarify what I am looking at? 有人可以澄清我在看什么吗?

Best I can understand is that this is an interface OrderPool which contains a property named Id of type string(array?) and something of type Level3Order ???? 我最能理解的是,这是一个OrderPool接口,其中包含一个名为Id的属性,类型为string(array?) ,类型为Level3Order ????

What is the relationship of Level3Order to the property Id and is Id an array or single instance? Level3Order与属性Id的关系是Level3Order ,Id是数组还是单个实例?

that means Objects that implement the interface OrderPool contain key/value pairs, where the key (called id in this case) is of type string and the value is of type Level3Order 这意味着实现接口OrderPool的对象包含键/值对,其中键(在本例中为id)的类型为string,而值的类型为Level3Order

for example this objects correctly implements the interface: 例如,此对象正确实现了接口:

{
  'item1': new Level3Order,
  'anotherItem': new Level3Order
}

You could also have something like 你也可以像

export interface OrderPool {
  [id: number]: Level3Order;
}

example: 例:

{
  1: new Level3Order(),
  5: new Level3Order()
}

What it means is simply, "If you index into something of type OrderPool , you get back something of type Level3Order ." 它的意思很简单,“如果索引到OrderPool类型的对象中 ,您将得到Level3Order类型的对象 。”

The type of the signature should always be string or number . 签名的类型应始终为字符串或数字 The name of the parameter ("id") is immaterial. 参数的名称(“ id”)无关紧要。

Take a look at the example below to get a complete idea. 请看下面的示例以获得完整的想法。

class Level3Order{
    public dummy : number = 0;
}

export interface OrderPool {
    [id :string]: Level3Order;
}

let pool : OrderPool ={}
pool["test"] = 5; //Error number is not assignable to Level3Order
pool["test"] = new Level3Order();  //Ok
pool["whatever"] = new Level3Order();  //Ok
pool.whatever =  new Level3Order(); //Still ok
pool["test"].dummy = 5; // Dummy is a property on Level3Order, Ok 

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

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