typescript 类型键值联动

  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' } })
  }
}

这样就可以完美解决问题

阅读 4.4k
2 个回答

interface 版本的暂时没想到,给一版函数式的先用着吧。

function basics<T extends keyof StoreActions>(type: T, data: StoreActions[T]) {
    // dosomething...
    return {
        type,
        data
    }
}

我也想看看有没有这种写法

我平常写的时候都是
interface Iprops{

xxx:string | number |Array<string>

}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进