Search code examples
angulartypescripttypescript-typingsreact-typescript

Typescript - Generic class with only two possible types


I'm trying to create a generic class where a property type has to be either string or number (because it's used as an index).

If I try something like the code below it will complain that

TS2536: Type 'T' cannot be used to index type '{}'.

export class GenericClass<T> {
    public selectionMap: {[id: T]: boolean} = {};

    public isSelected(id: T): boolean {
      return !!this.selectionMap[id];
    }

    public toggleSelected(id: T): void {
        if (this.isSelected(id)) {
            delete this.selectionMap[id];
        } else {
            this.selectionMap[id] = true;
        }
        this.onChange();
    }
}

In my case, I always know T will be a number or string. Just not sure how to write it down to stay type-safe.


Solution

  • Try the following:

    export class GenericClass<T = string | number> {}

    or

    export class GenericClass<T extends string, number> {}

    Also, make sure the types you are using to call the class are lowercase string and number. See this blog for further information.