我想弄清楚为什么 TypeScript 报告我的条件总是错误的,因为 Action.UP | 之间没有类型重叠。 Action.DOWN
和 Action.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
重新分配为 LEFT
或 RIGHT
,为什么条件总是 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/