接口的keyof和value的匹配对

时间:2019-04-19 08:15:05

标签: typescript

我有这样的界面:

interface ISession {
    emailAddress: string;
    me: IUser | null;
    groups: IGroup[] | null;
}

我想用这个伪代码创建一个对象:

type SetAction = {
    type: typeof SET,
    key: K in keyof ISession,
    value: V in valueof ISession
};

此伪代码的问题在于它不能确保值类型与ISession[k]的值匹配。

在TS中可以吗?

我对此有类似的问题,这不是问题的一部分,而是可以帮助其他人思考,因为我觉得解决方案是相同的。我需要编写一个函数function set(key, value)keyvalue在适当的匹配对中。

1 个答案:

答案 0 :(得分:2)

您可以创建这样的类型,但是您想要做的是创建所有可能的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

或者使用映射类型更容易理解版本(结果是相同的):

type SetAction = {
    [K in keyof ISession]-?: { type: typeof SET, key: K, value: ISession[K]; } 
}[keyof ISession]