1

我有一个带有 readonly 属性的类,我在function内部定义constructor,编译器发出一个我不知道如何解决的错误:

    class TEST {
        public readonly desc: string;

        constructor() {
            const compute = () => {
                this.desc = "description"
            };
        }
    }

编译器说:"Cannot assign to "desc" because it is a readonly property"但我认为在构造函数内部分配属性会避免这种错误。有可能还是我必须改变实施?

4

1 回答 1

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
    }
}
于 2019-01-04T15:21:21.653 回答