Reputation: 1801
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
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
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>;
Upvotes: 35
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
Upvotes: 5