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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With