Answer the question
In order to leave comments, you need to log in
Typescript. How to type callback?
I'm just starting to learn TS and now I'm faced with a misunderstanding of typing.
Let's take a simple Observer as an example.
TS observer
Everything is very simple, the class has an observers object in which an array of callbacks is stored by the event key.
The attach method subscribes the callback to the event.
detach unsubscribes.
The notify method, by event name, iterates through the array and calls all subscribers, passing arguments to them.
How to save the type of arguments passed to callback?
And in general, how to type it correctly?
Let's say in the inheriting class I will hang a handler,
this.attach('input', (value: string) => {
console.log(value.toUpperCase())
});
this.notify('input', 'Hello World!');
Answer the question
In order to leave comments, you need to log in
https://www.typescriptlang.org/play/?useDefineForC...
you can also make a conditional type for the subscriber, but you still have to implement branching, so it's better to use an overload, more clearly.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question