我有一个 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,
}
Run Code Online (Sandbox Code Playgroud)
我想删除一些样板文件,特别是通过将构造函数赋值替换为:
Object.assign(this, input);
Run Code Online (Sandbox Code Playgroud)
这保证了在构造的实例上设置输入字段。然而,Typescript 似乎并没有意识到这一点的效果。它抱怨说:
Property 'prop{1,2,3}' has no initializer and is not definitely assigned in the constructor.
Run Code Online (Sandbox Code Playgroud)
有没有办法解决这个问题,或者我是否一直在构造函数中重复每个属性名称?
要抑制错误,您可以使用明确的赋值断言:
class ModelAssert {
prop1!: string;
prop2!: string;
prop3!: string;
constructor(input: ModelInput) {
Object.assign(this, input);
}
}
Run Code Online (Sandbox Code Playgroud)
class ModelDeclare {
declare prop1: string;
declare prop2: string;
declare prop3: string;
constructor(input: ModelInput) {
Object.assign(this, input);
}
}
Run Code Online (Sandbox Code Playgroud)
取决于您希望如何将这些属性发送到 JavaScript。这比手动复制所有内容的工作量要少,但仍然需要在类中为输入中的每个属性进行声明。另请注意,如果您实际上忘记初始化属性,这些技术会抑制错误(删除该Object.assign()
行,您仍然不会收到警告)。
如果您真的根本不想进行声明,您可以使用一些类型断言实现类工厂函数,如下所示
function AssignCtor<T extends object>() {
return class {
constructor(t: T) {
Object.assign(this, t)
}
} as { new(t: T): T }
}
Run Code Online (Sandbox Code Playgroud)
然后用它来制作“接受类型参数T
并返回类型值T
”形式的构造函数。所以Model
可能是:
class Model extends AssignCtor<ModelInput>() {
method() {
console.log(this.prop1 + ", " + this.prop2 + ", " + this.prop3);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以验证它是否有效:
const model = new Model({ prop1: "hi", prop2: "okay", prop3: "bye" });
model.method(); // hi, okay, bye
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
563 次 |
最近记录: |