TypeScript中类如何实现200+属性的interface而无需重复声明所有属性
最优解决方案:利用TypeScript声明合并特性
只需要额外加一行同名接口继承的声明即可,不需要重复编写任何属性定义:
interface MyProperties { property1: string property2: string // ... 其余230个属性 property232: string } // 新增这一行即可 interface MyClass extends MyProperties {} class MyClass { constructor() { this.property1 = 'foo'; this.property2 = 'bar'; // ... 其余属性初始化 this.property232 = 'bar'; } }
原理
TypeScript 支持同名声明合并:同一作用域下的同名interface和class会自动合并类型定义,相当于给MyClass类隐式声明了所有MyProperties中定义的属性,不会缺失任何类型检查能力,也不需要修改原有类的逻辑代码。
替代方案:构造函数类型断言
如果你不想额外声明同名接口,可以直接将类的构造函数断言为返回MyProperties实例的类型:
interface MyProperties { property1: string property2: string // ... 其余属性 property232: string } const MyClass = class MyClass { constructor() { this.property1 = 'foo'; this.property2 = 'bar'; // ... 其余属性初始化 this.property232 = 'bar'; } // 关键是下面这行类型断言 } as new () => MyProperties
这种方案的效果和声明合并一致,但是要注意你需要自行确保构造函数中完成了所有属性的初始化,TS不会主动校验你是否遗漏了属性。
如果你的属性初始化可以整理成一个完整的配置对象,还可以结合Object.assign简化构造函数的代码:
interface MyClass extends MyProperties {} class MyClass { constructor() { const initProps: MyProperties = { property1: 'foo', property2: 'bar', // ... 其余属性赋值 property232: 'bar' } Object.assign(this, initProps) } }
内容的提问来源于stack exchange,提问作者cubefox
相关产品推荐
相关产品推荐

