interface StoreActions {
setUser: string
action1: string[]
action2: { test: string }
}
interface ActionsH extends AnyAction {
type: keyof StoreActions
// data:???
}
ActionsH的属性type
的值是StoreActions类型的键
string
string[]
{ test: string }
答案 0 :(得分: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
使接口通用,并使用通用键来设置数据属性的类型。 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]
}