我在function
内的constructor
内定义了一个具有只读属性的类,编译器发出了一个我不知道如何解决的错误:
class TEST {
public readonly desc: string;
constructor() {
const compute = () => {
this.desc = "description"
};
}
}
编译器说:"Cannot assign to "desc" because it is a readonly property"
,但我认为在构造函数中分配属性将避免此类错误。
有可能还是必须更改实施?
答案 0 :(得分:2)
您将需要类型断言来解决它,这是使用映射类型从类型中删除readonly
的最安全方式:
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
class TEST {
public readonly desc!: string;
constructor() {
const compute = () => {
(this as Mutable<TEST>).desc = "description"
};
}
}
readonly
是一个相当弱的修饰符,因此,如果您不介意将this
作为参数传递,则可以避免使用断言:
class TEST {
public readonly desc!: string;
constructor() {
const compute = (target: Mutable<TEST>) => {
target.desc = "description"
};
compute(this)// works fine and not just because we are in teh constructor
}
}