我在将值从基类实例映射到扩展类时遇到一些理解问题。有没有一种方法可以在不指定构造函数中的所有单独属性的情况下执行此操作?我不想这样做,以防其他开发人员将更多可选参数添加到基类中。 (此外,大约有 20 个这样的类,每个类都有 30 多个属性)
鉴于以下代码,在不“破坏” typescript 的情况下设置扩展类的值的最佳方法是什么。
export class BaseClass {
a: string;
b: string;
c: string;
}
export class ExtendClass extends BaseClass {
d: string;
e: string;
}
const exampleBase = {
a: 'help',
b: 'me',
c: 'please',
};
let exampleExtend: ExtendClass = exampleBase; // Is there a way do this ??
exampleExtend.d = 'hello';
exampleExtend.e = 'world';
let exampleExtend2: any = exampleBase; // Breaking typing
exampleExtend2.d = 'hello';
exampleExtend2.e = 'world';
我想知道是否有一种方法可以使用构造函数来实现此目的,但找不到将类分配给传入参数的方法...可能是因为这是心理上的。
export class BaseClass {
constructor(values?: BaseClass) {
if (values) {
this = values; // Is there a way to do this? I think not and for good reason.
}
}
a: string;
b: string;
c: string;
}
export class ExtendClass extends BaseClass {
constructor(values: BaseClass) {
super(values);
}
d: string;
e: string;
}
最佳答案
您正在寻找的是一个干净的构造函数和Object.assign
class Bar {
a: string;
b: string;
c: string;
constructor(obj) {
Object.assign(this, obj);
}
}
let bar = new Bar({a: 'foo', b: 'bar', c: 'baz'});
console.log(bar.a);
关于javascript - 设置扩展类基类值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49275382/