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:
typeof foo
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.
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.
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
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