使用 Object.assign 避免 Typescript 构造函数中的冗余

2023-12-12

我有一个 Typescript 应用程序,其中有很多这样的代码:

class Model {

  prop1: string;
  prop2: string;
  prop3: string;

  constructor(input: ModelInput) {
    this.prop1 = input.prop1;
    this.prop2 = input.prop1;
    this.prop3 = input.prop1;
  }

}

type ModelInput = {
  prop1: string,
  prop2: string,
  prop3: string,
}

我想删除一些样板文件,特别是通过将构造函数分配替换为:

Object.assign(this, input);

这保证了在构造的实例上设置输入字段。然而,Typescript 似乎并没有意识到这一点的效果。它抱怨说:

Property 'prop{1,2,3}' has no initializer and is not definitely assigned in the constructor.

有没有办法解决这个问题,或者我是否一直在构造函数中重复每个属性名称?


要抑制错误,您可以使用明确的赋值断言:

class ModelAssert {

  prop1!: string;
  prop2!: string;
  prop3!: string;

  constructor(input: ModelInput) {
      Object.assign(this, input);
  }

}

or declare属性修饰符:

class ModelDeclare {

  declare prop1: string;
  declare prop2: string;
  declare prop3: string;

  constructor(input: ModelInput) {
      Object.assign(this, input);
  }

}

取决于您希望如何将这些属性发送到 JavaScript。这比手动复制所有内容的工作量要少,但仍然需要在类中为输入中的每个属性进行声明。另请注意,如果您实际上忘记初始化属性,这些技术可以抑制错误(删除Object.assign()线,你仍然没有收到任何警告)。


如果您真的根本不想进行声明,您可以使用一些实现的类工厂函数类型断言像这样

function AssignCtor<T extends object>() {
    return class {
        constructor(t: T) {
            Object.assign(this, t)
        }
    } as { new(t: T): T }
}

然后用它来制作“采用类型参数”形式的构造函数T并返回一个类型的值T". So Model可能:

class Model extends AssignCtor<ModelInput>() {
    method() {
        console.log(this.prop1 + ", " + this.prop2 + ", " + this.prop3);
    }
}

您可以验证它是否有效:

const model = new Model({ prop1: "hi", prop2: "okay", prop3: "bye" });
model.method(); // hi, okay, bye

Playground 代码链接

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Object.assign 避免 Typescript 构造函数中的冗余 的相关文章

随机推荐