如何将属性更改为类中使用的静态值?

时间:2019-06-14 04:24:03

标签: typescript

class Parent {
    currentStatus: 'a' | 'b' | 'c';
}

class Test extends Parent {
    public static status = {
        a: 'a',
    };
    constructor() {
        super();
        this.currentStatus = Test.status.a;
    }
}

我应该怎么做?

我想将值放入CurrentStatus。

1 个答案:

答案 0 :(得分:1)

  

我想将值放在CurrentStatus中。

发生错误是因为我们无法将类型string分配给字符串文字联合类型'a' | 'b' | 'c'

您可以使用as const来确保Test.status.a属于字符串文字类型'a',它位于'a' | 'b' | 'c'的域之内,而不是扩展为类型string,在域之外。

class Parent {
    currentStatus: 'a' | 'b' | 'c';
}

class Test extends Parent {
    public static status = {
        a: 'a' as const,
    };

    constructor() {
        super();
        this.currentStatus = Test.status.a;
    }
}
相关问题