TypeScript 构造函数中解构参数属性

文章讨论了在TypeScript中如何使用parameterproperties简化构造函数,尤其是在参数较多时。虽然目前不支持直接将解构的对象与parameterproperties结合,但通过`Object.assign`和接口可以实现类似功能。示例代码展示了如何将一个对象分配给类的属性,同时提供了错误检查。这种方法对于处理JSON转换为类实例特别有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,需要同时导出 classinterface

尽管最后没用上 残念,不过感觉这个方法对于转换 JSON 到 JS 对象来说还是很方便的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值