typescript转换

144 阅读1分钟

interface Action {

payload?: T

type: string;

}

interface initInterface {

count: number;

message: string;

asyncMethod<T,U>(input: Promise<T>): Promise<Action<U>>;

syncMethod<T,U>(action:Action<T>): Action<U>;

}

interface newInitInterface {

asyncMethod<T,U>(input: Promise<T>) : Promise<Action<U>>;

transformAsyncMethod<T,U> (input: T) : Action<U>;

}

/**

  • 抽离initInterface中属于函数的key值

*/

type RemoveNonFunctionProps = {

[K in keyof T]: T[K] extends Function ? K : never

}[keyof T];

type FunctionProps = RemoveNonFunctionProps

/**

  • 根据抽离的函数key值抽离出函数

*/

type PickFunction = Pick<T, RemoveNonFunctionProps>;

type iFunctionInterface = PickFunction;

/**

  • 进行转换的规则定制

  • infer可以取到内部值

*/

type transformMethodTo = T extends (

input: Promise<infer U>

) => Promise<Action>

? (input: U) => Action<S>

: T extends (action: Action<infer U>) => Action<infer S>

    ? (action: U) => Action<S>

    : never;

/**

  • 转换接口

*/

type toNewInitInterface = {

[K in keyof T]: transformMethodTo<T[K]>

}

type connect = toNewInitInterface