我试图创建一个实现接口并具有构造函数方法的类,但这让我重复了很多代码。
这是一个例子:
export interface IComputer {
id: number;
model: string;
color: string;
screenSize: number;
language: string;
usbPorts: number;
ramGb: number;
brand: string;
year: number;
}
class Computer implements IComputer {
id: number;
model: string;
color: string;
screenSize: number;
language: string;
usbPorts: number;
ramGb: number;
brand: string;
year: number;
constructor(computer: IComputer) {
this.id = computer.id;
this.model = computer.model;
this.color = computer.color;
this.screenSize = computer.screenSize;
this.language = computer.language;
this.usbPorts = computer.usbPorts;
this.ramGb = computer.ramGb;
this.brand = computer.brand;
this.year = computer.year;
}
}
我认为这不是最好的命名每个属性三次来实现这一目标。有什么想法吗?
答案 0 :(得分:2)
DRYer类型安全版本是:
class Computer implements IComputer {
id: number = this.computer.id;
model: string = this.computer.model;
...
constructor(private computer: IComputer) {}
}
可以在类中跳过类属性的枚举,为了做到这一点,接口应该成为抽象类并被继承。然后应在类构造函数中枚举属性,以便从computer
参数中选取:
export abstract class IComputer {
id: number;
model: string;
...
}
class Computer extends IComputer {
constructor(computer: IComputer) {
super();
const keys = Object.keys(computer).filter(key => ['id', 'model', ...].includes(key));
for (const key of keys) {
this[key] = computer[key];
}
}
在这种情况下,无法保证一组拾取的属性将匹配接口属性。