Typescript从函数中删除第一个参数

时间:2019-11-08 10:33:05

标签: javascript typescript generics

我正在尝试使用打字稿进行建模的情况可能很奇怪。

我有一堆具有以下格式的函数

type State = { something: any }


type InitialFn = (state: State, ...args: string[]) => void

我希望能够创建一个表示InitialFn的类型,并删除第一个参数。像

// this doesn't work, as F is unused, and args doesn't correspond to the previous arguments
type PostTransformationFn<F extends InitialFn> = (...args: string[]) => void

这可能吗?

2 个答案:

答案 0 :(得分:4)

我认为您可以采用更通用的方式做到这一点:

type OmitFirstArg<F> = F extends (x: any, ...args: infer P) => infer R ? (...args: P) => R : never;

然后:

type PostTransformationFn<F extends InitialFn> = OmitFirstArg<F>;

PG

答案 1 :(得分:3)

您可以使用条件类型来提取其余参数:

type State = { something: any }

type InitialFn = (state: State, ...args: string[]) => void

// this doesn't work, as F is unused, and args doesn't correspond to the previous arguments
type PostTransformationFn<F extends InitialFn> = F extends (state: State, ...args: infer P) => void ? (...args: P) => void : never

type X = PostTransformationFn<(state: State, someArg: string) => void> // (someArg: string) => void

Playground Link

相关问题