Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - add one argument to a function's params

Tags:

typescript

type SomeFunc = (a:string, b:number, c:someCustomType) => number;

I want to create a type that is just like the one above, except there is a single parameter added at the end. Let's say, d:number;

type SomeFuncAltered = (a:string, b:number, c:someCustomType, d:number) => number;

I do not want to craft the entire type manually though, I'm pretty sure there's a smart trick with Parameters<func> to be used here.

like image 214
John Smith Avatar asked Dec 03 '25 16:12

John Smith


1 Answers

As the accepted answer here doesn't seem to work for me (using TS 4), I wrote my own type that adds any number of parameters to the end of a function.

type AddParameters<
  TFunction extends (...args: any) => any,
  TParameters extends [...args: any]
> = (
  ...args: [...Parameters<TFunction>, ...TParameters]
) => ReturnType<TFunction>;

Usage:

type SomeFunc = (a: string, b: number, c: someCustomType) => number;
type SomeFuncAltered = AddParameters<SomeFunc, [d: number]>;
// SomeFuncAltered = (a:string, b:number, c:someCustomType, d:number) => number;

Note: This solution also allows you to add named parameters.

like image 138
Melody Universe Avatar answered Dec 06 '25 13:12

Melody Universe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!