打字稿接口键值链接



code

interface StoreActions {
setUser: string
action1: string[]
action2: { test: string }
}
interface ActionsH extends AnyAction {
type: keyof StoreActions
// data:???
}

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

期望

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

有可能实现吗?如何实现?

这里有几个选项。

  1. 使用所有可用类型的可区分并集。可以使用映射类型生成联合。这可能是更好的解决方案,因为TypeScript通常能够缩小类型范围。操场

    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. 使接口泛型,并使用泛型中的键来设置数据属性的类型。操场

    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]
    }
    

最新更新