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?
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)
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)
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