【问题标题】:Typescript typeguard on the first generic element of a type类型的第一个通用元素上的打字稿类型保护
【发布时间】:2021-03-02 09:16:38
【问题描述】:

我有一个Actions 类型,需要映射到actionMap 变量中的一组回调。

但是,我不确定如何强制Action 类型的第一个通用元素的类型。显然key in keyof Actions 没有在这里做事。我需要改用什么?

export interface Action<T, U> {
  type: T,
  data: U,
}

export type Actions =
  | Action<"something", {}>
  | Action<"somethingElse", {}>

const actionMap: { [key in keyof Actions]: (action: Actions) => any } = {
  // I'd like the value of the `type` property of all my actions enforced here. Ex:
  // "something": (action) => {}
  // "somethingElse": (action) => {}
}

如果我问错了问题,什么是更好的问题?我不确定我是否使用了相应的行话。

【问题讨论】:

    标签: typescript generics types keyof typeguards


    【解决方案1】:

    您可以通过使用索引访问类型来获取接口的属性,并使用Extract 在函数中缩小action 的类型来实现这一点。

    export interface Action<T, U> {
      type: T,
      data: U,
    }
    
    export type Actions =
      | Action<"something", { something: true}>
      | Action<"somethingElse", { somethingElse: true }>
    
    const actionMap: { [K in Actions['type']]: (action: Extract<Actions, { type: K }>) => any } = {
      "something": (action) => {}, // TS knows action.data.something exists
      "somethingElse": (action) => {} // TS knows action.data.somethingElse exists
    }
    

    【讨论】:

    • 太棒了!我会确保阅读更多内容:)
    猜你喜欢
    • 2018-06-08
    • 2017-05-18
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多