Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use string indexed interface of typescript?

I'd like to use string index of interface.

interface IDictionary {      [index: string]: string; } var params: IDictionary; params = [{ "heart": "HP" }, { "mana": "MP" }]; console.log(params); 

I thought this might be like MAP such as a pair of key and value. I'm not sure this is correct approach.

like image 716
idpokute Avatar asked Mar 13 '15 22:03

idpokute


People also ask

How can you use string as a index type in TypeScript?

The "Type 'String' cannot be used as an index type" TypeScript error occurs when we use the String type instead of string (lowercase s ). To solve the error, make sure to use the string type with lowercase s in your TypeScript code.

What is index type in TypeScript?

The indexing type is itself a type, so we can use unions, keyof , or other types entirely: type I1 = Person ["age" | "name"]; type I1 = string | number. type I2 = Person [keyof Person ]; type I2 = string | number | boolean.

How do I inherit an interface in TypeScript?

Interfaces and Inheritance An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.

How do I create a index signature in TypeScript?

Index signature syntax The syntax of an index signature is pretty simple and looks similar to the syntax of a property, but with one difference. Instead of the property name, you simply write the type of the key inside the square brackets: { [key: KeyType]: ValueType } .


1 Answers

Using the indexer limits what can be put or fetched for the object using the index syntax. E.g. foo is inferred to be of type string:

interface IDictionary {      [index: string]: string; } var params = {} as IDictionary;  params['heart'] = 'HP'; // okay var foo = params['heart']; // foo:string 

The following on the other hand is an error as it will not type check:

var bar:number = params['heart']; // ERROR params['heart'] = 234; // ERROR 

Complete demo:

interface IDictionary {      [index: string]: string; } var params = {} as IDictionary;  params['heart'] = 'HP'; // okay var foo = params['heart']; // foo:string   var bar:number = params['heart']; // ERROR params['heart'] = 234; // ERROR 
like image 197
basarat Avatar answered Sep 21 '22 21:09

basarat