如何简化TypeScript类中解构构造器参数初始化成员变量的冗余代码
给你几个简化代码的方案:
方案1:提取参数类型接口,减少重复定义
先把构造函数参数的类型抽成独立接口,避免重复写类型约束,同时保留你用的ES原生私有字段(#开头):
import * as ē from 'three' interface CylindricCurveOptions { eqs: ((θ: number) => number)[] scale: number rounds?: number mainAxis?: 'x' | 'y' } export class cylindricCurve extends ē.Curve { #scale: number #eqs: ((θ: number) => number)[] #rounds: number #mainAxis: 'x' | 'y' | null constructor({ eqs, scale = 1, rounds = 1, mainAxis = null, }: CylindricCurveOptions) { super() this.#scale = scale this.#eqs = eqs this.#rounds = rounds this.#mainAxis = mainAxis } }
这样每个成员的重复次数从五次降到三次,类型约束只写一次,代码清爽很多。
方案2:用TypeScript参数属性,彻底省掉手动赋值
如果你能接受TypeScript的private修饰符(和ES原生#私有字段功能类似,只是编译后是普通属性,无法通过运行时语法强制隐藏),可以直接在构造函数参数前加private,TypeScript会自动帮你创建类成员并完成赋值,代码直接缩成这样:
import * as ē from 'three' export class cylindricCurve extends ē.Curve { constructor( private eqs: ((θ: number) => number)[], private scale: number = 1, private rounds: number = 1, private mainAxis: 'x' | 'y' | null = null ) { super() } }
这个方案里每个变量名只出现一次,完全省去了手动定义成员和赋值的步骤,简洁到极致。
方案3:字段默认值+参数覆盖(保留ES私有字段)
要是你必须用ES原生私有字段,还可以把默认值直接写在字段初始化里,构造函数只处理传入参数的覆盖:
import * as ē from 'three' interface CylindricCurveOptions { eqs: ((θ: number) => number)[] scale?: number rounds?: number mainAxis?: 'x' | 'y' } export class cylindricCurve extends ē.Curve { #scale: number = 1 #eqs: ((θ: number) => number)[] #rounds: number = 1 #mainAxis: 'x' | 'y' | null = null constructor(options: CylindricCurveOptions) { super() const { eqs, scale, rounds, mainAxis } = options this.#eqs = eqs if (scale !== undefined) this.#scale = scale if (rounds !== undefined) this.#rounds = rounds if (mainAxis !== undefined) this.#mainAxis = mainAxis } }
这里用undefined判断避免覆盖默认值(比如传入0这种 falsy 值不会被错误忽略),同时减少了构造函数里的重复代码。
内容的提问来源于stack exchange,提问作者punund
相关产品推荐
相关产品推荐

