7

Trying to access a property of dict with dot notation makes Typescript complain. The language specification, 4.10, states:

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.

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? 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?

1
  • This behavior surprises me as well. Even after reading the answer, I feel we should be able to reference property of interfaces with the dot notation. Commented Dec 31, 2016 at 18:44

1 Answer 1

3

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:

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
Sign up to request clarification or add additional context in comments.

2 Comments

I seem to have a hard time understanding the concept of the dictionary pattern. In the example I mentioned, it there a way to define an interface for dict that allows for checking that the key should be String and the value Function? Or is var dict: any the best solution here?
key string is always allowed. The index signature only restricts what the value can be. That said I mostly use index signatures for documentation purposes, not type-safety.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.