how to use string indexed interface of typescript?

34,820

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
Share:
34,820

Related videos on Youtube

idpokute
Author by

idpokute

Hello Folks I like Wordpress, because it is not only my first CMS in my life, but also its echo. If I can help its community, it would be a great pleasure. Currently I handle JS and PHP as a full-time Wordpress developer. I spend my spare times with learning English, Japanese, and other programming stuff. For instance, WP-REST, Gutenberg, React, Vue, and game dev. Thank you

Updated on September 23, 2020

Comments

  • idpokute
    idpokute over 3 years

    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.

  • mejdev
    mejdev over 8 years
    Don't forget you need to initialize params.. params = {};