I know that key/value objects in TypeScript are typed like this:
const animals: { [key: string]: string } = { a1: "cat", a2: "dog" };
The above object only allows values of type string.
Now, let's say I have this abstract class
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("roaming the earth...");
}
}
How can I make it so that my animals
object can only have actual animals, i.e. classes (not instances) that extends Animal
?
I've tried this, but get "cannot find name 'T'" as an error.
const animals: { [key: string]: T extends typeof Animal } = { a1: Cat, a2: Dog };
const animal = new animals["a2"]();
Also tried this, but get "'?' expected"
const animals: { [key: string]: any extends typeof Animal } = { a1: Cat, a2: Dog };
const animal = new animals["a2"]();
If I knew all types of animals beforehand (but I don't) this would work:
const animals: { [key: string]: typeof Cat | typeof Dog } = { a1: Cat, a2: Dog };
const animal = new animals["a2"]();
Is there a way to make this generic?
{ [key: string]: typeof Animal }
work for you? Also you could write it nicer asRecord<string, typeof Animal>
– Alex Chashinanimals["a2"]
toany
first before trying to create an instance, since otherwise the compiler would complain aboutAnimal
being abstract. – slothAnimal
non-abstract{ [key: string]: typeof Animal }
should work... – sloth