Natasha
Natasha

Reputation: 441

TypeScript: Something similar to ReturnType<...> needed but for the type of the first function argument

Is it possible in TypeScript to declare something like ReturnType<...> that does not retrieve the type of the return value but the type of the first argument instead?

type SingleArgFunction<A, R> = (arg: A) => R

// wrong => how to implement the following line correctly?
type FirstArgType<T extends SingleArgFunction<infer A, any>> = A 

const numberToString: SingleArgFunction<number, string> =
    (x: number) => String(x)

type R = ReturnType<typeof numberToString> // R => string

type F = FirstArgType<typeof numberToString> // F => number

Upvotes: 0

Views: 59

Answers (1)

WayneC
WayneC

Reputation: 5740

Looks like this does what you want:

type FirstArgumentType<T> = T extends (arg1: infer U, ...args: any[]) => any ? U : never;

Upvotes: 3

Related Questions