为什么类型在枚举中没有重叠?

Li3*_*357 5 enums typescript reactjs

我试图弄清楚为什么 TypeScript 报告我的条件总是为 false,因为在这种情况下Action.UP | Action.DOWN和之间没有类型重叠(游乐场链接):Action.LEFT

class Component<S> {
    public state: S;
    public render() {}
}

enum Action {
    UP,
    DOWN,
    LEFT,
    RIGHT,
}

interface State {
    action: Action;
}

const initialAction: Action.UP | Action.DOWN = Action.UP;
class MyComponent extends Component<State> {
    public state = {
        action: initialAction,
    }

    public render() {
        // Why is action not of type Action as declared in the interface?
        const isLateral = this.state.action === Action.LEFT;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果this.state.action只有 type 的初始值,但在接口中Action.UP | Action.DOWN声明为 type ,为什么我不能将其与 进行比较?如果我将来可以重新分配为or ,为什么条件总是 false ?ActionAction.LEFTthis.state.actionLEFTRIGHT

Sha*_*tin 3

回答“为什么?”

为什么操作不是接口中声明的 Action 类型?

它是一种不同的类型,因为子类正在重新定义属性state并为其提供比父类中更窄的类型。如果您按照设计这样做,那么您可以通过内部转换来访问父类的更广泛的接口render()

const isLateral = (this as Component<State>).state.action === Action.LEFT;
Run Code Online (Sandbox Code Playgroud)

推荐方法

或者,按照React 组件文档的说明进行操作:

...如果您的组件需要使用本地状态,请直接在构造函数中将初始状态分配给 this.state :

即不重新重新定义父类的state属性;相反,使用为您提供的已定义state属性extend。在构造函数中设置其初始值。

class MyComponent extends Component<State> {

    constructor() { 
        super();
        this.state = {
            action: initialAction,
        }
    }

    public render() {
        const isLateral = this.state.action === Action.LEFT;
    }
}
Run Code Online (Sandbox Code Playgroud)