我正在定义一个带有由接口(interface)定义的构造函数参数的 typescript 类,它将属性限制为仅定义的属性。
以下代码片段按预期工作,但是,有没有办法减少代码,使其不那么重复?每个属性都提到了 4 次,一定有更好的方法。
interface MyInterface {
property1: string;
property2: boolean;
property3: number;
}
class MyClass {
property1: string;
property2: boolean;
property3: number;
constructor(parameters: MyInterface) {
this.property1 = parameters.property1;
this.property2 = parameters.property2;
this.property3 = parameters.property3;
}
}
const example = new MyClass({property1: "Property 1", property2: true, property3: 3, extraProperty: "Shouldn't exist"});
console.log(example);
编辑:我还需要在运行时限制具有额外未知属性的对象的属性。
最佳答案
这个怎么样?
interface MyInterface {
property1: string;
property2: boolean;
property3: number;
}
class MyClass implements MyInterface {
property1: string;
property2: boolean;
property3: number;
constructor(parameters: MyInterface) {
Object.assign(this, parameters);
}
}
关于typescript - Typescript 类/接口(interface)定义是否有更好的简写形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69675991/