MDalt
MDalt

Reputation: 1801

Typescript remove first argument from a function

I have a possibly weird situation that I'm trying to model with typescript.

I have a bunch of functions with the following format

type State = { something: any }


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

I would like to be able to create a type that represents InitialFn with the first argument removed. Something like

// 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

Is this possible?

Upvotes: 21

Views: 8911

Answers (3)

jdk905
jdk905

Reputation: 625

I've landed on this question a few times now because I can never remember the name of the OmitThisParameter<Type> utility exported from Typescript as of version 3.3. The OmitThisParameter<Type> is not as generic as the solution posted by @georg, but has always been what I've been looking for when I stumble across this question. Hopefully someone else finds this helpful as well (at the bare minimum I'll see it next time I forget the name of the utility)

Upvotes: 2

georg
georg

Reputation: 214949

I think you can do that in a more generic way:

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

and then:

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

PG

Upvotes: 35

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

You can use a conditional type to extract the rest of the parameters:

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

Upvotes: 5

Related Questions