我是 typescript 的新手,我的代码有很多重复的引用(data1、data2、data3...)。
export interface ProjectInterface{
data1: string;
data2: string;
data3: number;
}
export class Project {
data1: string;
data2: string;
data3: number;
constructor(obj: ProjectInterface) {
this.data1 = obj.data1;
this.data2 = obj.data2;
this.data3 = obj.data3;
}
}
我知道我可以在构造函数中传递数据 1、数据 2...但是当你有很多参数时它并不方便。
是否有一个干净的解决方法来保持接口(interface)具有单一的引用入口点?
最佳答案
i'd like to avoid repeating variables declarations in Project Class and automatize the initialization
虽然这肯定不会在所有 情况下削减它,但在您的情况下您可以使用 Object.keys迭代 obj
自己的属性,同时执行一些基本的类型检查:
constructor(obj: ProjectInterface) {
Object.keys(obj).forEach(key => {
if (this.hasOwnProperty(key) && typeof this[key] == typeof obj[key]) {
this[key] = obj[key];
}
});
}
然而,这需要您将属性初始化为合理的默认值,否则 hasOwnProperty
将返回 false。
注意 ES6 arrow function保留了 this
的正确词法范围。
关于OOP/Typescript - 当类构造函数将接口(interface)对象作为参数时,是否可以优化代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40002991/