When designing a generic class, I am faced with the requirement that a property type must be either a string or number to serve as an index.
If attempting something like the code snippet below, the following error will be triggered:
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 scenario, I can confidently assert that T will always be of type number or string. However, I am unsure of the correct syntax to maintain type safety in this case.