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

标签 reactjs typescript enums

我想弄清楚为什么 TypeScript 报告我的条件总是错误的,因为 Action.UP | 之间没有类型重叠。 Action.DOWNAction.LEFT 在这种情况下 (playground link):

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;
    }
}

如果this.state.action只有一个初始值Action.UP | Action.DOWN,但在界面中声明为类型Action,为什么我不能将其与Action.LEFT进行比较?如果我将来可以将 this.state.action 重新分配为 LEFTRIGHT,为什么条件总是 false?

最佳答案

回答“为什么?”

Why is action not of type Action as declared in the interface?

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

const isLateral = (this as Component<State>).state.action === Action.LEFT;

推荐方法

或者,执行 React Component documentation 的操作说:

...if your component needs to use local state, assign the initial state to this.state directly in the constructor:

即不要重新定义父类的状态属性;相反,使用 extend 给你的已经定义的 state 属性。在构造函数中设置它的初始值。

class MyComponent extends Component<State> {

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

    public render() {
        const isLateral = this.state.action === Action.LEFT;
    }
}

关于reactjs - 为什么在枚举中类型没有重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54449973/

相关文章:

reactjs - 获取 react 组件的大小?

javascript - 在 React.js 中使用 chrome api

javascript - 在dygraphs中表示枚举数据

JAVA 子枚举声明

Java 枚举作为 BigInteger 值

reactjs - 受控的 TextField 在键盘输入每个字符后失去焦点

javascript - 如何通过 Django 正确地服务于我的 React 生产构建。当前配置存在 MIME 类型问题

typescript - 想要强制一个特定类型的函数,但想要在 TypeScript 中有一个默认值

javascript - 语法错误 : Unexpected token : when running jest test with Aurelia in TypeScript

angular - 如何在不使用angular 2+中的ngmodel的情况下为输入设置一个值