You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript具名参数的构造函数简写方案咨询

TypeScript 具名参数构造函数的简洁写法

TypeScript 的构造函数参数属性简写确实实用,能大幅减少冗余代码:

简洁写法:

class Dog {
  constructor(
    public age: number,
    public weight: number,
  ) {}
}

替代原本的冗长写法:

class Dog {
  public age: number
  public weight: number

  constructor(
    age: number,
    weight: number,
  ) {
    this.age = age
    this.weight = weight
  }
}

你提到的具名参数(对象解构)传参new Dog({age: 3, weight: 8})确实更清晰,能避免参数位置错误,但默认写法存在多处重复,不符合DRY原则。目前TypeScript没有原生支持解构参数的参数属性简写,但可以通过以下方式实现简洁且符合DRY的写法:

方案1:提取接口 + Object.assign

先定义一个包含所有属性的接口,再通过Object.assign一次性完成属性赋值:

interface DogProps {
  age: number;
  weight: number;
}

class Dog implements DogProps {
  age: number;
  weight: number;

  constructor(props: DogProps) {
    Object.assign(this, props);
  }
}

// 使用方式
const dog = new Dog({ age: 3, weight: 8 });
console.log(dog.age); // 3

这种写法只需要在接口中定义一次属性类型,类实现接口保证类型一致,构造函数通过Object.assign避免手动赋值,彻底消除重复。

方案2:解构参数 + 接口(简化版)

如果不想用Object.assign,也可以直接解构参数,但依然复用接口来避免类型重复:

interface DogProps {
  age: number;
  weight: number;
}

class Dog implements DogProps {
  age: number;
  weight: number;

  constructor({ age, weight }: DogProps) {
    this.age = age;
    this.weight = weight;
  }
}

相比你原来的写法,这种方式把类型定义提取到接口中,只需要写一次属性类型,减少了两处重复。

额外技巧:利用类型别名简化

如果不想用接口,也可以用类型别名替代,效果一致:

type DogProps = {
  age: number;
  weight: number;
};

class Dog {
  constructor(private props: DogProps) {}

  // 如果需要直接访问属性,可以添加getter
  get age() {
    return this.props.age;
  }

  get weight() {
    return this.props.weight;
  }
}

这种写法更简洁,但属性会挂载在props属性下,需要通过getter直接暴露,适合属性较多的场景。

内容的提问来源于stack exchange,提问作者Anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 13:12:40