带有扩展运算符的 Typescript 构造函数

标签 typescript

如果与扩展运算符一起使用,则需要将属性分配给从接口(interface)定义的唯一属性。

我期待使用带有扩展运算符的 typescript 构造函数的解决方案。

例如。

export interface IBrand {
    id: string;
    name: string;
}

export class Brand implements IBrand {
    id: string;
    name: string;       

    constructor(data: IBrand) {
        this.id = data.id;
        this.name = data.name;
    }
}

这是一种选择,所以当我这样称呼这个类时,不知道有多少成员,但我只有 id, name到最终对象。
new Brand({...data })

案例:但是当我有 25 个以上的 key 时 data
export interface IBrand {
    id: string;
    name: string;
}

export class Brand implements IBrand {
    id: string;
    name: string;       

    constructor(data: Partial<IBrand>) {
        Object.assign(this, data);
    }
}

我希望不要再次编写所有属性的构造函数。不管它有 25 个,它只是分配现有的属性将被分配。如果数据有 section, genre或任何其他属性,它将被忽略。

我的第二个片段不起作用。

最佳答案

这不使用扩展运算符,但您可以使用 this answer 中的方法

constructor(data: IBrand) {
    for (let key in data) {
        this[key] = data[key];
    }
}

然后实例化...
new Brand(data);

关于带有扩展运算符的 Typescript 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56040302/

相关文章:

angular - getter 和 setter 中 Observable 的 Typescript 返回类型

javascript - Typescript 泛型未返回正确的类型

typescript - 为什么 Typescript 代码是(或不是)循环依赖?

typescript - 如何使用 tsconfig 编译单个 TS 文件?可选地在 ts-node 中?

javascript - typescript + lodash - 找不到模块

typescript - 检查属性是否存在的类型保护

javascript - Angular 2 - API 请求未返回 Observable,错误 : undefined has no property 'length'

reactjs - 在我的自定义 React hook 中,是否可以编写一个可以动态返回有效的 firebase 查询的函数?

javascript - 在类本身中初始化 TypeScript 变量与在构造函数中初始化变量之间的区别

javascript - 等待音乐加载时的 ionic 旋转器( ionic 2/Angular 2)