代码之家  ›  专栏  ›  技术社区  ›  Noitidart

接口的keyof和valueof的匹配对

  •  1
  • Noitidart  · 技术社区  · 6 年前

    我有这样一个界面:

    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) . 在哪里 key value

    2 回复  |  直到 6 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    6 年前

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