interface StoreActions {
setUser: string
action1: string[]
action2: { test: string }
}
interface ActionsH extends AnyAction {
type: keyof StoreActions
// data:???
}
类型 ActionsH 的属性 type
的值是 类型 StoreActions 的 key
期望:
当 type = 'setUser' 时, data 的类型是 string
当 type = 'action1' 时, data 的类型是 string[]
当 type = 'action2' 时, data 的类型是 { test: string }
请问有没有实现的可能? 如何实现?
@_未缪 感谢,这是一个有价值的方案, 我受到启发并找到了答案
我把 ActionsH 接口修改为:
interface ActionsH<K extends keyof StoreActions> extends AnyAction {
type: K
data: StoreActions[K]
}
然后添加:
interface StoreProps {
dispatch: <T extends keyof StoreActions>(options: ActionsH<T>) => void
}
在业务代码中使用:
@withStore
class Demo extends React.Component<StoreProps, {}>{
componentDidMount(){
this.props.dispatch({ type: 'action2', data: { test: '123' } })
}
}
这样就可以完美解决问题
interface 版本的暂时没想到,给一版函数式的先用着吧。