1

I am defining the interface for a hash:

export interface Hash<ValType> {
    [key: string | number]: ValType;
}

This errors:

An index signature parameter type must be 'string' or 'number'. (parameter) key: string | number

Then I tried:

export interface Hash<KeyType extends number | string, ValType> {
    [key: KeyType]: ValType;
}

Same error.

How can I achieve this?

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
  • 1
    check both answers to this question https://stackoverflow.com/questions/46885489/can-a-typescript-generic-constraint-provide-allowed-types – dbandstra Nov 17 '17 at 07:08

1 Answers1

0

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.

Fenton
  • 241,084
  • 71
  • 387
  • 401