您可以创建这样一个类型,但您要做的是创建一个所有可能类型的并集
key
/
value
组合。所以我们要创建的类型是:
type SetAction =
{ type: typeof SET, key: 'emailAddress', value: string; } |
{ type: typeof SET, key: 'me', value: IUser | null; } |
{ type: typeof SET, key: 'groups', value: IGroup[] | null; }
我们可以通过使用
distributive conditional type
type SetAction = keyof ISession extends infer K ? // introduce type parameter
K extends keyof ISession ? // distribute over the type parameter
{ type: typeof SET, key: K, value: ISession[K]; } // The type that we construct for each K
: never: never
或者使用映射类型的PerfHap版本更易于理解(结果相同):
type SetAction = {
[K in keyof ISession]-?: { type: typeof SET, key: K, value: ISession[K]; }
}[keyof ISession]