[英]Typescript: assign a readonly attribute in a function inside the constructor
I have a class with a readonly attribute that I define inside a function
inside the constructor
, the compiler issues an error I do not know how to solve: 我有一个具有只读属性的类,该类在constructor
function
内部的function
定义,编译器发出错误,我不知道如何解决:
class TEST {
public readonly desc: string;
constructor() {
const compute = () => {
this.desc = "description"
};
}
}
The compiler says: "Cannot assign to "desc" because it is a readonly property"
but I thought that assigning the property inside the constructor will avoid this kind of errors. 编译器说: "Cannot assign to "desc" because it is a readonly property"
但我认为在构造函数内部分配该属性将避免此类错误。 Is it possible or do I have to change implementation? 有可能还是必须更改实施方式?
You will need a type assertion to get around it, the safest way it to use a mapped type that removes readonly
from the type: 您将需要类型断言来解决它,这是使用映射类型从类型中删除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
is a rather weak modifier, so if you don't mind passing in this
as a parameter, you can avoid the assertion: 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.