reactjs - 如何简洁地实现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'
但推断是所有动作的有效负载的联合:
为了使有效负载类型推断起作用,我在这里缺少什么?
解决方案
你可以试试
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
}
}
推荐阅读
- hazelcast - Hazelcast VersionedPortalble 的使用
- jquery - AJAX响应后如何通过jQuery设置表单
- spring-boot - 具有多个模块的 Spring 数据不起作用
- python - 当我使用 Bootstrap 的模式时,我的 Django 表单没有呈现
- c# - 将 WCF SOAP 和 WCF REST 服务托管为 Azure 应用服务
- c++ - 如何在 C++ 中的每个嵌套循环的新列中打印输出?
- javascript - 赛普拉斯点击后做某事
- sql-server - 如何在sql的执行键中编写函数
- node.js - 使用节点创建像 react/open-wc 这样的脚手架生成器
- angular - 将服务从 Angular 2/4 更新到 Angular 7