Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a generic function in as a callback in Typescript

Tags:

typescript

I'm trying to preserve the type information of arguments to a callback, where the callback is a generic:

function Foo<Template>(argument: Template) {
  // Do something with argument
}

function Bar(callback: Function) {
  callback('something')
}

let x = Bar( Foo<String> )

This does not look like valid typescript syntax. Any way to do this?

like image 917
OneChillDude Avatar asked Nov 16 '25 07:11

OneChillDude


2 Answers

Expanding on the answer of Rodrigo here. If you have a function with a generic:

function doSomething<T>(t: T): void {
    console.log("oh " + t);
}

You can define the type of the function as follows:

type Handler = <T>(t: T) => void;

Then you can use the type Handler as a function parameter:

function thisFirst(callback: Handler) {
  callback<string>('boink');
}

thisFirst(doSomething)
like image 197
Kokodoko Avatar answered Nov 19 '25 02:11

Kokodoko


You can define a generic function for callback with a generic argument like this:

const handleSomething =
  <T extends (...args: Parameters<T>) => ReturnType<T>>(callback: T) =>
  (...args: Parameters<T>) =>
    callback(...args)
   
like image 36
Anros Nguyen Avatar answered Nov 19 '25 01:11

Anros Nguyen



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!