Reputation: 773
i have class hierarchy that looks like this:
interface TypeI {
getName(): string;
}
class ClassA implements TypeI{
static name: string = "A"
getname(){
return ClassA.name;
}
}
class ClassB implements TypeI{
static name: string = "B"
getname(){
return ClassB.name;
}
}
Is it possible to make Dictionary of types that implement TypeI in typescript? Something like this:
var typedDictionary: { [<T extends TypeI>] : T };
typedDictionary[ClassA] = new ClassA();
var a: ClassA = typedDictionary[ClassA];
Upvotes: 2
Views: 1928
Reputation: 276353
Dictionary of types that implement TypeI in typescript?
Keys for objects in javascript can only be a string. If you pass in something that is not a string then toString
will be called on it. So no, you cannot have a type T
as a key ... only a string
.
You could however abstract over it in a class and that is something like this generic Dictionary does: https://github.com/basarat/typescript-collections#a-sample-on-dictionary
Upvotes: 1