Typescript: Get the type of the last parameter of a function type

后端 未结 4 822
花落未央
花落未央 2021-01-05 16:32

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

4条回答
  •  自闭症患者
    2021-01-05 17:18

    Here is yet a another solution which is a slight modification of jcalz answer to make it more generic using some recursive conditional types:

    type Head = T extends [any, ...any[]] ? T[0] : never;
    type Tail =
        ((...t: T) => any) extends ((_: any, ...tail: infer U) => any)
            ? U
            : [];
    type HasTail = T extends ([] | [any]) ? false : true;
    
    type Last = {
        0: Last>
        1: Head
    }[
        HasTail extends true ? 0 : 1
    ];
    
    type LastType = Last>; // boolean
    

    It might be interesting to consider replacing any with unknown as well.

提交回复
热议问题