【发布时间】:2020-07-07 15:46:26
【问题描述】:
我有一个接口,它的属性是可选的,但它在我的构造函数中设置了默认值,然后被从构造函数的第一个参数传入的值覆盖。如果未设置属性,则使用默认值。
我怎样才能得到它,以便参数在传递给构造函数时仍然是可选的,但在类中使用时,它被视为已设置。我不想得到以下错误:
对象可能是“未定义”。
export interface IMain {
req: string;
prop?: ISecondary;
}
export interface ISecondary {
a?: string;
b?: string;
}
export class ABC {
public main: Main;
public constructor(main: Main) {
this.main.prop = {
a: "A",
b: "B",
...main.prop
};
}
public doSomething() {
this.main.prop.a = "Z";
}
}
new ABC({
req: 'cat'
});
【问题讨论】:
标签: javascript typescript