Typescript 是否有一种方法可以使用变量实例化参数列表中带有可选参数的类?
我希望根据变量的值选择性地实例化各种类 正如这个Stackblitz所显示的,如果构造函数中没有参数,那么它可以正常工作,但是如果构造函数中有参数,那么它就会失败 如果构造函数中有参数,我是做错了什么,还是根本没有办法实现我的目标Typescript 是否有一种方法可以使用变量实例化参数列表中带有可选参数的类?,typescript,Typescript,我希望根据变量的值选择性地实例化各种类 正如这个Stackblitz所显示的,如果构造函数中没有参数,那么它可以正常工作,但是如果构造函数中有参数,那么它就会失败 如果构造函数中有参数,我是做错了什么,还是根本没有办法实现我的目标 // WITH PARAMETERS export class Foo { prop1: string; constructor(prop1: string="foo!") { console.log("Foo constructor: "+prop1
// WITH PARAMETERS
export class Foo {
prop1: string;
constructor(prop1: string="foo!") {
console.log("Foo constructor: "+prop1);
}
}
// WITHOUT PARAMETERS
export class Bar {
prop1: string;
constructor() {
this.prop1 = "bar!";
console.log("Bar constructor:"+this.prop1)
}
}
试验台:
export class HelloComponent {
@Input() name: string;
objClasses = {
foo: Foo,
bar: Bar
}
ngOnInit() {
let thisTypeOne = this.objClasses.foo;
let myFooObj = new (thisTypeOne)();
let anotherFooObj = new (thisTypeOne)("bazz");
console.log("My Foo Obj: " + myFooObj.prop1); // *** Undefined
console.log("Another Foo Obj: " + anotherFooObj.prop1); // *** Undefined
let thisTypeTwo = this.objClasses["bar"];
let myBarObj = new (thisTypeTwo)();
console.log("My Bar Obj: "+myBarObj.prop1); // *** bar!
您可以使用
Object.create(proto[propertiesObject])
,将类名传递给此函数,它将返回对象。但是属性部分应该定义为一个对象,因此不能直接将参数传递给构造函数。所以在你的代码中试试这个
let anotherFooObj=Object.create(thisTypeOne,{prop1:{value:“buzz”})代码>您忘记在构造函数中设置instance属性-TypeScript不会自动执行此操作
export class Foo {
prop1: string;
constructor(prop1: string="foo!") {
console.log("Foo constructor: "+prop1);
this.prop1 = prop1;
}
}
这段代码似乎丢失了类的prop1
属性-Bar
构造函数设置了它,但它没有定义。请完成这个示例,这样我们就可以帮助您了。顺便说一句,不需要定义它,因为代码应该在没有显式声明的情况下运行,但我在Stackblitz中以任何方式添加了声明。还是一样的结果。另外,请随时进行Stackblitz,并做出您认为合适的任何更改,非常感谢您的反馈,并帮助我理解这一点!