首页 > 解决方案 > 如何简洁地实现reducer函数的类型推断?

问题描述

有很多关于输入 reducer 函数的例子,但它们似乎对我来说太冗长了。我试图保持简短和简单,并编写了我的操作和减速器类型如下:

行动

interface Actions {
  VISIBLE: "yes" | "no"
  LOCATION: { x: number; y: number }
}

行动

interface Action<T extends keyof Actions> {
  type: T
  payload: Actions[T]
}

对于以下示例,完美地为有效负载键入智能感知:

const example : Action<'VISIBLE'> = {type: 'VISIBLE', payload: 'yes'}

然而,在下面的 reducer 函数中,即使 action 的类型很明确,payload 的类型也不会像我预期的那样推断出来:

const myReducer = (
  state: any,
  action: Action<keyof Actions>
) => {
  switch (action.type) {
    case 'VISIBLE':
      const example = action.payload
  }
}

我希望example这里的类型被推断为,'yes' | 'no'但推断是所有动作的有效负载的联合:

“示例”变量的类型推断结果

为了使有效负载类型推断起作用,我在这里缺少什么?

标签: reactjstypescript

解决方案


你可以试试

interface Actions {
  VISIBLE: "yes" | "no"
  LOCATION: { x: number; y: number }
}

interface Action<T extends keyof Actions> {
  type: T
  payload: Actions[T]
}

// Add custom typings here
type A = {
  [K in keyof Actions] : Action<K> 
}[keyof Actions]


const myReducer = (
  state: any,
  action: A
) => {
  switch (action.type) {
    case 'VISIBLE' :
      const example = action.payload
  }
}

操场


推荐阅读