【问题标题】:Typescript constructor with spread operator带有扩展运算符的打字稿构造函数
【发布时间】:2019-09-26 03:52:28
【问题描述】:

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

我期待使用带有扩展运算符的 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 个以上的 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 或任何其他属性,它将被忽略。

我的第二个 sn-p 不起作用。

【问题讨论】:

  • 但是构造函数之前没有现有的属性。
  • 如果您希望在运行时发生某些事情,您需要提及 "id""name" 作为运行时值。最简单的方法是在数组中提及这些键。 (例如,在 TS3.4 中,(["id", "name"] as const).forEach(k =&gt; this[k] = data[k]);)。避免在接口/类和运行时重复单词"id""name" 的唯一方法是创建一个包含这些名称的运行时常量数组,然后从中派生接口/类定义(而不是其他方法是行不通的),但为了避免编写一些字符串文字,这是很多类型的杂耍。

标签: typescript


【解决方案1】:

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

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

然后实例化...

new Brand(data);

【讨论】:

    【解决方案2】:

    我使用class-transformer 包找到了更好的重复代码解决方案。它还有助于公开输入并将其转换为所需的输出。

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多