Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending another TypeScript function with additional arguments

Tags:

typescript

Is it possible in TypeScript 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 BaseType adds or changes arguments this should also be reflected in my overloaded function type.

Is this possible?

like image 577
Thomas Avatar asked Sep 12 '18 11:09

Thomas


Video Answer


2 Answers

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;
like image 100
Titian Cernicova-Dragomir Avatar answered Oct 20 '22 17:10

Titian Cernicova-Dragomir


You could use spread with Parameters<>:

function base(a: number, b: number, c: number): number
function derived(add: string, ...base: Parameters<typeof base>): number

The restriction is that base parameters have to be on the end.

like image 21
Gerold Meisinger Avatar answered Oct 20 '22 17:10

Gerold Meisinger