Bil*_*ill 13 constructor class readonly-attribute typescript
我有一个简单的类,我想在构造函数启动的方法中为只读属性赋值,但它说[ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property.
为什么即使我process从构造函数调用,我也不能为属性赋值?
示例代码:
class C {
readonly readOnlyProperty: string;
constructor(raw: string) {
this.process(raw);
}
process(raw: string) {
this.readOnlyProperty = raw; // [ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property.
}
}
Run Code Online (Sandbox Code Playgroud)
我通常使用这种解决方法。
private _myValue = true
get myValue (): boolean { return this._myValue }
Run Code Online (Sandbox Code Playgroud)
现在您可以从类内部更改属性,并且该属性在外部是只读的。这种变通方法的一个优点是您可以重构您的属性名称而不会产生错误。这就是为什么我不会使用这样的东西(this as any).readOnlyProperty = raw。
小智 6
除了 "casting" this as any,您仍然可以通过修改此属性来强制执行类型检查:
(this.readOnlyProperty as string) = raw; // OK
(this.readOnlyProperty as string) = 5; // TS2322: Type '5' is not assignable to type 'string'.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14297 次 |
| 最近记录: |