简体   繁体   English

为什么在TypeScript中接口可以同时具有数字和字符串索引签名?

[英]Why is it possible to have both numeric and string index signatures for an interface in TypeScript?

According to the language specification it is possible to have an interface with both numeric and string index signature, so the following interface seems to be valid: 根据语言规范,可以同时具有数字和字符串索引签名的接口,因此以下接口似乎是有效的:

interface WeirdArray {
  [index: string]: string;
  [index: number]: string;
}

But I can't find a suitable example where such an interface can be used, can someone provide an example where such an interface makes sense? 但是我找不到可以使用这种接口的合适示例,有人可以提供一个这样的接口有意义的示例吗?

Because the number indexer type has to be a subtype of the string indexer type, it's not terribly useful unless you had some crazy type where the string-named properties were of some base type and the number-named properties were a subtype of that type. 因为数字索引器类型必须是字符串索引器类型的子类型,所以除非您有某种疯狂的类型,其中字符串命名的属性是某种基本类型,数字命名的属性是该类型的子类型,否则它并不是非常有用。 I can't imagine a use for this. 我无法想象这有什么用。

In short, it's allowed because it's not disallowed . 简而言之,允许这样做是因为不允许这样做

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

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