Mr-haili / aaa-blog

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

todo 函数映射

Mr-haili opened this issue · comments

commented

参考:
https://stackoverflow.com/questions/48011353/how-to-unwrap-type-of-a-promise/49889856

export type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

export type MyArgumentType<F> = F extends (...args: infer A) => any ? A : [undefined];

type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

type MappedOutputs<T> = {
    [P in keyof T]: MyReturnType<T[P]>
}

type FuncMap = { [key in string]: (request: any) => Promise<any> };

type ThenArg<T> = T extends PromiseLike<infer U> ? U : T

// 定义
type MyMappedOutputFuncs<T extends FuncMap> = {
  [P in keyof T]: () => ThenArg<ReturnType<T[P]>>;
}

type MyMappedInputFuncs<T extends FuncMap> = {
  [P in keyof T]: (payload: Parameters<T[P]>[0]) => void;
}

const funcMap = {
  aFunc: async (x1: string) => "123",
  bFunc: async (x2: number) => 123,
  cFunc: async (x1: { a: string, b: number }) => x1
}

type AFuncMap = typeof funcMap;

/**
 * 传入一组函数的 map 返回函数返回值的 map
 */
function getReturnVals(funcMap: AFuncMap) {
  const actions: MyMappedInputFuncs<AFuncMap> = {
    "aFunc": () => {},
    "bFunc": () => {},
    "cFunc": () => {},
  };
  const selectors: MyMappedOutputFuncs<AFuncMap> = {
    aFunc: () => "123",
    bFunc: () => 123,
    cFunc: () => {
      return { a: "123", b: 235 }
    }
  };
  return {
    actions,
    selectors
  }
}


// 混合的 hashMap
type AKey = "a" | "b";
type BKey = "c" | "d";
type A = { [key in AKey]: string } & { [key in BKey]: boolean }  & { [key in string]: number };