我有一个带有解构构造函数参数的类:
import * as ē from 'three'
export class cylindricCurve extends ē.Curve {
#scale: number
#eqs: ((θ: number) => number)[]
#rounds: number
#mainAxis: 'x' | 'y'
constructor({
eqs,
scale = 1,
rounds = 1,
mainAxis = null,
}: {
eqs: ((θ: number) => number)[]
scale: number
rounds?: number
mainAxis?: 'x' | 'y'
}) {
super()
this.#scale = scale
this.#eqs = eqs
this.#rounds = rounds
this.#mainAxis = mainAxis
}
如您所见,这非常冗长,每个名称都被提及五次只是为了初始化成员变量。我想知道是否有更简洁的方法来完成任务。
很难证明是否定的,但是虽然你可以通过不解构来摆脱其中的一个,但我认为你会被其他的困住,因为你无法从构造函数参数(就像使用 TypeScript 的
public
、protected
和 private
参数注释一样;甚至那些你必须拥有离散参数而不是解构的参数)。
这是为了完整性而进行的微小更改:
import * as ē from 'three'
export class cylindricCurve extends ē.Curve {
#scale: number
#eqs: ((θ: number) => number)[]
#rounds: number
#mainAxis: 'x' | 'y'
constructor(props: { // ***
eqs: ((θ: number) => number)[]
scale: number
rounds?: number
mainAxis?: 'x' | 'y'
}) {
super()
this.#scale = props.scale ?? 1 // ***
this.#eqs = props.eqs // ***
this.#rounds = props.rounds ?? 1 // ***
this.#mainAxis = props.mainAxis ?? null // ***
}
}
在 TypeScript 中发现一个已有八年历史的问题后 (https://github.com/Microsoft/TypeScript/issues/5326),我尝试遵循其中一种解决方法:
import * as ē from 'three'
export class cylindricCurve extends ē.Curve {
private scale: number = 1
private eqs: ((a: number) => number)[]
private rounds?: number = 1
private mainAxis?: 'x' | 'y' = null
constructor(_: cylindricCurve) {
super()
Object.assign(this, _)
}
}
虽然这有效,但我对这种方法不太满意,它看起来不必要的老套,并且缺乏灵活性:现在每个属性都注定是有效的构造函数参数。