typescript - Typescript 类/接口(interface)定义是否有更好的简写形式?

标签 typescript class shorthand

我正在定义一个带有由接口(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/

相关文章:

angularjs - 在不迭代数组的情况下从 Angular 生成标记

java - Android:在 onVideoEnd() 中播放下一个提示视频

python - 如果 __init__ 中未定义该属性,则显示该类的属性?

php - 存储 PHP 类属性的最佳方式是什么?

css - Safari 中的多个背景

typescript - 如果我的网站已经在使用 moment.min.js,如何使用 Moment.js TypeScript 定义文件?

c# - 工具版本不支持 VsTsc 任务

angular - Angular 2 中的 routerLink 显示为纯文本

javascript - 我可以在 Javascript 中使用简写 if && 执行多个语句吗?

properties - C++/CLI 速记属性