typescriptoverloading

Extending another TypeScript function with additional arguments


Is it possible in to define a function type and extend its argument list in another type (overloading function type?)?

Let's say I have this type:

type BaseFunc = (a: string) => Promise<string>

I want to define another type with one additional argument (b: number) and the same return value.

If at some point in the future BaseFunc adds or changes arguments this should also be reflected in my overloaded function type.


Solution

  • You can use Tuples in rest parameters and spread expressions together with conditional type and the inference behavior of conditional types to extract the parameters from the signature and reconstruct the new signature.

    type BaseFunc = (a: string) => Promise<string>
    
    type BaseWithB  = BaseFunc extends (...a: infer U) => infer R ? (b: number, ...a:U) => R: never;