Typescript: dot notation access property using dictionary type

Trying to access the dict property with dotted notation, Typescript complains. The language specification, 4.10, states:

ObjExpr [IndexExpr]

... if the objExpr with the visible type has a string signature of the index and IndexExpr is of type Any, the type of the String or Number primitive, or the type of the enumeration, access to the properties refers to the type of this index signature.

I use:

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 should it be allowed? But this is obvious. What is my mistake and how can I change the code so that I can dial the dict and access properties using dot notation?

+5
source share
1 answer

For:

resource access refers to the type of this index signature

Access to properties in this case is a bracket:

 interface MapStringToFunction { [index: string]: Function; } var dict: MapStringToFunction = {}; dict['say'] = () => 'hi'; dict['say'](); 

More details

Below will be a compile time error:

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

In our case, a function is the only type of property that allows you to:

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

However, in order to be able to use any property, it must be declared

Otherwise, it will open too much insecure type access. For example , if what you offer is allowed, the following will only work at run time and not compile time :

 interface MapStringToFunction { [index: string]: Function; } var dict: MapStringToFunction = {}; dict.say() // Runtime error, as undefined is not callable 
+2
source

Source: https://habr.com/ru/post/1202764/


All Articles