Assume I have a function type, e.g.
type somefntype = (a: number, b: string, c: boolean) => void
I need the type of that function types
Update: TypeScript 4.0 introduced variadic tuple types, which means that Last
can now be implemented simply as
type Last = T extends [...infer I, infer L] ? L : never;
And the rest works as normal:
type LastParameterany> = Last>;
type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter // boolean
Playground link to code
TypeScript 3.0 introduced tuple types in rest and spread expressions, specifically to allow programmatic conversion between the types of function parameter lists and tuples. There's a type alias called Parameters
defined in the standard library that returns the parameter list of a function as a tuple.
It's annoying but possible to get the last element of a tuple type with a fixed but arbitrary length:
// Tail returns a tuple with the first element removed
// so Tail<[1, 2, 3]> is [2, 3]
// (works by using rest tuples)
type Tail =
((...t: T)=>void) extends ((h: any, ...r: infer R)=>void) ? R : never;
// Last returns the last element of the tuple
// (works by finding the one property key in T which is not in Tail)
type Last = T[Exclude>];
Putting those together you get
type LastParameterany> = Last>;
And we can test it:
type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter // boolean
Looks good to me. Link to code