R
R
Rustam2020-06-09 15:55:22
typescript
Rustam, 2020-06-09 15:55:22

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())
 });

value should be a string, but how to specify what types the callback parameters will have in Observer, because in another class I can hang another handler with different parameters.

Same issue with alerts. those. when calling the notify method
I would like that, when filling in the event argument in notify, TS prompted me which parameters can be passed. Or what events are available. Is this even possible? I looked at how the bind function was typed in typescript, and realized that there is no simple solution: D I did the same with attach, but it did not solve the problem with notify any, I don’t use
this.notify('input', 'Hello World!');



Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-06-09
Demonov @Demonov

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 question

Ask a Question

731 491 924 answers to any question