typescript 从构造函数调用的方法中为“只读”属性赋值

kpbwa7wx  于 2022-12-19  发布在  TypeScript
关注(0)|答案(5)|浏览(158)

我有一个简单的类,我想给构造函数初始化的方法中的一个只读属性赋值,但是它说[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.
    }
}
krugob8w

krugob8w1#

我通常使用以下解决方法:

private _myValue = true
get myValue (): boolean { return this._myValue }

现在您可以从类内部更改属性,从外部更改属性为readonly
这个解决方案的一个优点是你可以重构你的属性名,而不会产生错误,这就是为什么我不会使用这样的代码:

(this as any).readOnlyProperty = raw
sulc1iza

sulc1iza2#

您不应强制转换this as any,而应仅通过修改此属性来强制执行类型检查:

// OK
(this.readOnlyProperty as string) = raw; 

// TS2322: Type '5' is not assignable to type 'string'.
(this.readOnlyProperty as string) = 5;
eivgtgni

eivgtgni3#

当你创建一个单独的函数来赋值时,这个单独的函数可以从其他地方使用,而不是从唯一的构造函数使用。编译器不会检查(对于一个公共函数,甚至不能检查)这个函数是否只从构造函数调用。所以错误。
无论如何,你有两种方法来赋值,一种是把你的独立函数的核心放到构造函数中,另一种是,会让你失去类型检查,所以不推荐,除非你真的知道你在做什么,将this转换成any

(this as any).readOnlyProperty = raw
nbysray5

nbysray54#

很老的问题,但我认为这仍然值得分享我通常是如何克服这个问题的。我倾向于返回你想从方法中设置的值,然后你仍然分离逻辑,同时保持只读,没有任何可以论证的非法旁路。

class C {
    readonly readOnlyProperty: string;
    constructor(raw: string) {
        this.readOnlyProperty = this.process(raw);
    }
    process(raw: string) {
         // ...some logic that processes 'raw'...

        return raw;
    }
}
koaltpgm

koaltpgm5#

试试看

Object.assign(this, {readOnlyProperty: raw})

相关问题