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.
CodePudding user response:
Why are you using generics in this case? Just use the types you want to have or define a type that fits your needs:
type Id = number | string;
export class GenericClass {
public selectionMap: {[id: Id]: boolean} = {};
public isSelected(id: Id): boolean {
return !!this.selectionMap[id];
}
public toggleSelected(id: Id): void {
if (this.isSelected(id)) {
delete this.selectionMap[id];
} else {
this.selectionMap[id] = true;
}
this.onChange();
}
}
CodePudding user response:
Try the following:
export class GenericClass<T = string | number> {}
or
export class GenericClass<T extends string, number> {}