It isn't possible to use a generic for the key on an indexer. Instead, you need to create an interface for each key type:
export interface StringHash<T> {
[key: string]: T;
}
export interface NumberHash<T> {
[key: number]: T;
}
const x: StringHash<Example> = {};
const y: NumberHash<Example> = {};
Hopefully you can see that if the generic key worked, it wouldn't save you any effort non-working example to demonstrate:
export interface Hash<TKey, T> {
[key: TKey]: T;
}
const x: Hash<string, Example> = {};
const y: Hash<number, Example> = {};
If this were possible, all you'd be achieving is moving where the word string
and number
appears in the expression each time you reference the Hash
. (i.e. it moves from NumberHash
to Hash<number,
).
This was discussed in issue #6641.