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

后端 未结 4 825
花落未央
花落未央 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条回答
  •  萌比男神i
    2021-01-05 17:16

    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

提交回复
热议问题