Typescript 类型体操 —— 实现 Lookup

1,036 阅读1分钟

要求

上一篇文章中,我们通过Extract处理了联合类型部分相交的情况;本题要求从联合类型中选出一部分满足特定条件的情况。

// 在联合`UpdateAction | RemoveAction`中搜索公共`type`字段来获取相应的类型。
enum ActionEnum {
    update,
    remove
}

interface UpdateAction {
    type: ActionEnum.update,
    payload: {
        updateData: string
    }
}

interface RemoveAction {
    type: ActionEnum.remove,
    payload: {
        removeData: number
    }
}

// result
type res = YourTypeFunc<UpdateAction | RemoveAction, ActionEnum.update>
//Expect UpdateAction

知识点

  1. A conditional type T extends U ? X : Y is either resolved to X or Y, or deferred because the condition depends on one or more type variables.

知识链接

  1. 泛型
  2. 条件类型

问题 & 解答

场景

export enum TagActionEnums {
    remove,
    update,
}

export type Action = {
    type: TagActionEnums.remove;
    payload: {
        id: number;
    }
} | {
    type: TagActionEnums.update;
    payload: {
        id: string;
    }
}

type LookUp<U extends TagActionEnums> = Extract<Action, { type: U }>['payload']
declare const handleRemove: (payload: LookUp<TagActionEnums.remove>) => void;
declare const handleUpdate: (payload: LookUp<TagActionEnums.update>) => void;
export const reducer = (action: Action) => {
switch(action.type){
    case TagActionEnums.remove:
        handleRemove(action.payload);
        break;
    case TagActionEnums.update:
        handleUpdate(action.payload);
        break;
    }
};