Typescript接口键值链接

时间:2019-12-11 01:40:09

标签: typescript

代码

  interface StoreActions {
    setUser: string
    action1: string[]
    action2: { test: string }
  }

  interface ActionsH extends AnyAction {
    type: keyof StoreActions
    // data:???
  }

ActionsH的属性type的值是StoreActions类型的键

期望

  • 当type ='setUser'时,数据类型为string
  • 当type ='action1'时,数据类型为string[]
  • 当type ='action2'时,数据类型为{ test: string }

能否实现?如何实现?

1 个答案:

答案 0 :(得分:1)

您在这里有两个选择。

  1. 使用所有可用类型的discriminated union。您可以生成具有映射类型的联合。这可能是更好的解决方案,因为TypeScript通常可以缩小类型。 Playground

    interface StoreActions {
        setUser: string
        action1: string[]
        action2: { test: string }
    }
    
    type MakeUnion<T> = {
        [K in keyof T]: { type: K, data: T[K] }
    }[keyof T]
    
    
    interface AnyAction {
        other: 'common properties that all actionsH members have'
    }
    
    type ActionsH = MakeUnion<StoreActions> & AnyAction
    
  2. 使接口通用,并使用通用键来设置数据属性的类型。 Playground

    interface StoreActions {
        setUser: string
        action1: string[]
        action2: { test: string }
    }
    
    interface AnyAction {
        other: 'common properties that all actionsH members have'
    }
    
    interface ActionH<K extends keyof StoreActions> extends AnyAction {
        type: K
        data: StoreActions[K]
    }