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

lf5gs5x2  于 2023-02-25  发布在  TypeScript
关注(0)|答案(3)|浏览(198)

我有一个可能很奇怪的情况,我试图用 typescript 建模。
我有一堆函数,格式如下

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

这可能吗?

p4rjhz4m

p4rjhz4m1#

我想你可以用一种更通用的方式来做:

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

然后:

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

PG级

laawzig2

laawzig22#

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

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链接

jfgube3f

jfgube3f3#

这个问题我已经提过几次了,因为我从来都记不住从Typescript导出的3.3实用程序的名称,OmitThisParameter<Type>不像@georg发布的解决方案那样通用。但当我偶然发现这个问题时,我一直在寻找答案。希望其他人也能发现这一点(至少下次我忘记实用程序的名称时会看到它)

相关问题