TypeScript 构造函数中解构参数属性
parameter properties 是一个挺方便的功能,对于不少 JS 的对象来说,构造函数基本是这样的用法:
class Example {
constructor(param1, param2) {
this.param1 = param1;
this.param2 = param2;
// ...
}
}
如果构造函数中的参数比较多——大概十几二十个——处理起来就会很麻烦,使用 parameter properties 可以很大程度地简化这个过程,如:
class Params {
constructor(
public readonly x: number,
protected y: number,
private z: number
) {
// No body necessary
}
}
不过有个问题就是很多时候从 JSON 或者是其他函数中返回的是一个对象,而不是解构的变量。
这是 feature 一个从 2015 年就开了的 issue:Combining destructuring with parameter properties #5326,不过到现在 TS 队伍好像还没有考虑要实现……


我试了一下 thread 中的一些建议,不过到现在还没成功过……
在 Stack Overflow 上有一个 code snippet: Destructured parameter properties in constructor,测试了一下是可以用的:
interface DestructedOptions {
prefix: string;
suffix: string;
}
class Destructed {
constructor(opts: DestructedOptions) {
Object.assign(this, opts);
}
}
interface Destructed extends DestructedOptions {}
let destructed = new Destructed({ prefix: 'prefix', suffix: 'suffix' });
console.log(destructed.prefix);
console.log(destructed.suffix);
console.log(destructed.DoesntExist); // error
使用的方法还是 Object.assign 搭配 TS 的 interface 会重载同名对象的特点去实现,这时候如果要导出 Destructed,需要同时导出 class 和 interface。
尽管最后没用上 残念,不过感觉这个方法对于转换 JSON 到 JS 对象来说还是很方便的。
文章讨论了在TypeScript中如何使用parameterproperties简化构造函数,尤其是在参数较多时。虽然目前不支持直接将解构的对象与parameterproperties结合,但通过`Object.assign`和接口可以实现类似功能。示例代码展示了如何将一个对象分配给类的属性,同时提供了错误检查。这种方法对于处理JSON转换为类实例特别有用。
1985

被折叠的 条评论
为什么被折叠?



