There is a custom type I've developed to extract the type of the second parameter in a function:
type SecondParam<T> = T extends (a: any, b: infer R) => any
? R
: never;
For the most part, it functions correctly:
type T1 = SecondParam<(x: any, y: number) => void>; // number
type T2 = SecondParam<(x: any, y: { x: string[] }) => void>; // { x: string[] }
However, when the second parameter is absent, I want it to return void
instead of an empty object:
type T3 = SecondParam<(x:any) => any> // currently {}, but I prefer void
I'm utilizing the SecondParam
type to specify another function's type:
type F<T> = (p: SecondParam<T>) => void;
type F1 = F<(x: any, y: number) => any>; // (p: number) => void
type F2 = F<(x: any, y: { x: string[] }) => any>; // (p: { x: string[] }) => void
type F3 = F<(x: any) => any>; // currently (p: {}) => void, but I prefer () => void
Unfortunately, it doesn't handle cases where the second parameter is missing as desired.