您可以使用“智能”设置器来实现此目的。想法是在类上定义一个 setter,从其自身中删除 setter,并通过使用属性设置为Object.defineProperty
的描述符调用的方法定义一个只读属性。writable
false
“类本身的变化”部分可以通过另一个属性重新定义来实现。不要忘记首先制作财产configurable
。
这是完整的样子(我认为没有更优雅的方法可以做到这一点) - 答案的运行时版本不是 TypeScript 特定的:
class ReadonlyFields {
set fixed(value) {
Object.defineProperty(this, "fixed", {
value,
writable: false,
configurable: true,
});
}
doSomething() {
Object.defineProperty(this, "fixed", {
value: 24, //exact logic for changing the value is up to you
writable: false
});
}
}
const r = new ReadonlyFields();
r.fixed = 42;
console.log(r.fixed); //42;
r.fixed = 24;
console.log(r.fixed); //42;
r.doSomething();
console.log(r.fixed); //24;
如果您还想从类型系统的角度强制执行此操作,只需创建属性readonly
:
class ReadonlyFields {
readonly fixed!: number;
setFixed(value: number) {
Object.defineProperty(this, "fixed", {
value,
writable: false,
configurable: true,
});
}
doSomething() {
Object.defineProperty(this, "fixed", {
value: 24, //exact logic for changing the value is up to you
writable: false,
});
}
}
const r = new ReadonlyFields();
r.setFixed(42); //OK
//@ts-expect-error
r.fixed = 24;
r.doSomething(); //OK