简体   繁体   English

typescript:使用'字典'类型的点符号访问属性

[英]typescript: access property with dot notation using 'dictionary' type

Trying to access a property of dict with dot notation makes Typescript complain. 尝试使用点表示法访问dict的属性会使Typescript抱怨。 The language specification, 4.10, states: 语言规范4.10规定:

ObjExpr [ IndexExpr] ObjExpr [IndexExpr]

... if ObjExpr 's apparent type has a string index signature and IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature. ...如果ObjExpr的表观类型具有字符串索引签名且IndexExpr的类型为Any,String或Number原始类型或枚举类型,则属性访问属于该索引签名的类型。

I am using: 我在用:

interface MapStringToFunction {
  [index: string]: Function;
}

var dict: MapStringToFunction = {};

dict.say = () => 'hi';

dict.say();

MapStringToFunction has a sting index signature and say is of type String, so it should be allowed? MapStringToFunction有一个sting索引签名,并且say是String类型,所以应该允许它? But it obvious is not. 但显而易见的不是。 What is my mistake and how can I change to code so I can type dict and access properties with dot notation? 我的错误是什么?如何更改代码以便我可以使用点表示法键入dict和访问属性?

For: 对于:

the property access is of the type of that index signature 属性访问属于该索引签名的类型

Property access in this case is the bracket notation: 在这种情况下,属性访问是括号表示法:

interface MapStringToFunction {
  [index: string]: Function;
}

var dict: MapStringToFunction = {};

dict['say'] = () => 'hi';

dict['say']();

More 更多

The following will be a compile time error: 以下是编译时错误:

interface MapStringToFunction {
  [index: string]: Function;
  say: number; // Eroor
}

In our case, Function is the only property type that is allows: 在我们的例子中,Function是唯一允许的属性类型:

interface MapStringToFunction {
  [index: string]: Function;
  say: Function;
}

However to be able to use any property it must be declared 但是,为了能够使用任何属性,必须声明它

Otherwise it would open up too much type-unsafe access. 否则会打开太多类型不安全的访问。 For example if what you propose was allowed the following would only fail at runtime and not compile time : 例如, 如果您建议允许以下内容,则只会在运行时失败而不是编译时间

interface MapStringToFunction {
  [index: string]: Function;
}

var dict: MapStringToFunction = {};

dict.say() // Runtime error, as undefined is not callable

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

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