打字稿从函数中删除第一个参数

MDa*_*alt 11 javascript generics typescript

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

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

type State = { something: any }


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

Run Code Online (Sandbox Code Playgroud)

我希望能够创建一个表示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

Run Code Online (Sandbox Code Playgroud)

这可能吗?

geo*_*org 14

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

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

进而:

type PostTransformationFn<F extends InitialFn> = OmitFirstArg<F>;
Run Code Online (Sandbox Code Playgroud)

PG


Tit*_*mir 5

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

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
Run Code Online (Sandbox Code Playgroud)

游乐场链接