It is not possible to assign classes dynamically because classes are defined at compile time, and during compilation of the animal class, the type T is unknown.
One workaround is to define a property with type T inside the animal class.
interface dog {
breed: string;
}
export class animal < T > {
actual: T;
legs: number;
}
export class main {
private mydog: animal < dog > = new animal < dog > ();
constructor() {
this.mydog.legs = 4;
this.mydog.actual.breed = "husky"; // This will throw an error because 'actual' is undefined (you must set it first)
}
}
If you need the animal class to be generic for a specific reason, another approach could be to have the dog class extend the animal class.
export class animal {
legs: number;
}
class dog extends animal {
breed: string;
}
export class main {
private mydog: dog = new dog();
constructor() {
this.mydog.legs = 4;
this.mydog.breed = "husky";
}
}