Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript copying only function arguments and not return type

Tags:

typescript

I have some util methods and I'm wondering if there's a way to copy arguments from one method to another. I was playing around with typeof and trying to type the 2nd function that way but I can't quite figure it out.

declare function foo(a: number, b: string): number;

now I want a type bar to have foo's arguments, but not the return type, for example let's say it calls foo but doesn't return anything:

const bar = (...args) => { foo(...args); }

Now I can declare bar to have the exact same type as foo:

const bar: typeof foo = (...args) => { foo(...args); }

but the return type doesn't match now. So how do I either:

  • Just copy the argument signature
  • Change the return type I get from typeof foo
like image 387
Nobody Avatar asked Mar 27 '19 21:03

Nobody


People also ask

How do you pass a function as argument TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

How do you get a return type of function in TypeScript?

Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.


1 Answers

There's built-in Parameters type

declare function foo(a: number, b: string): number;

type fooParameters = Parameters<typeof foo>;

declare const bar: (...parameters: fooParameters) => void;
// inferred as const bar: (a: number, b: string) => void 
like image 185
artem Avatar answered Nov 01 '22 08:11

artem