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