Typescript:在构造函数内部的函数中分配一个只读属性

时间:2019-01-04 15:08:53

标签: typescript constructor readonly-attribute

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

    class TEST {
        public readonly desc: string;

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

编译器说:"Cannot assign to "desc" because it is a readonly property",但我认为在构造函数中分配属性将避免此类错误。 有可能还是必须更改实施?

1 个答案:

答案 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
    }
}