有没有办法在TypeScript类中拥有动态对象属性,并为TypeScript添加动态类型?我看到类似的问题,但是没有像这样完整的示例。
interface IHasObjectName {
objectName: string;
}
class example<A extends IHasObjectName, B extends IHasObjectName> {
constructor(a: A, b: B) {
this[a.objectName] = function() { return a; };
this[b.objectName] = function() { return b; }
}
}
class Cat implements IHasObjectName {
objectName: string = "";
}
class Dog implements IHasObjectName {
objectName: string = "";
}
let cat = new Cat();
cat.objectName = "Cat";
let dog = new Dog();
dog.objectName = "Dog";
let test = new example<Cat,Dog>(cat, dog);
// ??? TYPESCRIPT DOESN'T KNOW ABOUT THESE DYNAMIC PROPERTIES
// HOW DO I MAKE THIS WORK?
let d = test.Dog();
let c = test.Cat();
// I know I could access like this
// let d = test["Dog"]();
// but I want to access like function and have it typed