打字稿:在构造函数内的函数中分配只读属性
Typescript: assign a readonly attribute in a function inside the constructor
我有一个 class,我在 constructor
的 function
中定义了一个只读属性,编译器发出一个错误,我不知道如何解决:
class TEST {
public readonly desc: string;
constructor() {
const compute = () => {
this.desc = "description"
};
}
}
编译器说:"Cannot assign to "desc" because it is a readonly property"
但我认为在构造函数中分配 属性 可以避免这种错误。
有可能还是我必须更改实施?
你需要一个类型断言来绕过它,最安全的方法是使用从类型中删除 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
}
}
我有一个 class,我在 constructor
的 function
中定义了一个只读属性,编译器发出一个错误,我不知道如何解决:
class TEST {
public readonly desc: string;
constructor() {
const compute = () => {
this.desc = "description"
};
}
}
编译器说:"Cannot assign to "desc" because it is a readonly property"
但我认为在构造函数中分配 属性 可以避免这种错误。
有可能还是我必须更改实施?
你需要一个类型断言来绕过它,最安全的方法是使用从类型中删除 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
}
}