Object index key type in Typescript

Robert Koritnik picture Robert Koritnik · Jan 26, 2017 · Viewed 81.8k times · Source

I defined my generic type as

interface IDictionary<TValue> {
    [key: string|number]: TValue;
}

But TSLint's complaining. How am I supposed to define an object index type that can have either as key? I tried these as well but no luck.

interface IDictionary<TKey, TValue> {
    [key: TKey]: TValue;
}

interface IDictionary<TKey extends string|number, TValue> {
    [key: TKey]: TValue;
}

type IndexKey = string | number;

interface IDictionary<TValue> {
    [key: IndexKey]: TValue;
}

interface IDictionary<TKey extends IndexKey, TValue> {
    [key: TKey]: TValue;
}

None of the above work.

So how then?

Answer

Nickeat picture Nickeat · Jan 26, 2017

You can achieve that just by using a IDictionary<TValue> { [key: string]: TValue } since numeric values will be automatically converted to string.

Here is an example of usage:

interface IDictionary<TValue> {
    [id: string]: TValue;
}

class Test {
    private dictionary: IDictionary<string>;

    constructor() {
       this.dictionary = {}
       this.dictionary[9] = "numeric-index";
       this.dictionary["10"] = "string-index"

       console.log(this.dictionary["9"], this.dictionary[10]);
    }
}
// result => "numeric-index string-index"

As you can see string and numeric indices are interchangeable.