How to type a constant with string-defined functions?
Solution 1:
Let's start typing EventHandler
and figure this out.
First of all it's an object:
type EventHandlerType = {};
It has keys that are EVENTs
// Create a mapped type mapping events to anything
type EventHandlerType = { [e in EVENT]: any }
Every value is a function that takes a data parameter and returns void
// Create a mapped type mapping events to anything
type EventHandlerType = { [e in EVENT]: (data: any) => void };
Which should work in your code:
const EventHandler: { [key in EVENT]: (data: any) => void } = {
[EVENT.FIRST_EVENT]: (data: any) => {
console.log(`Hello there, ${data.blue_player}`);
}
}
This is made simpler with the built in utility type Record
which exists for these cases:
const EventHandler: Record<EVENT, (data: any) => void> = {
[EVENT.FIRST_EVENT]: (data: any) => {
console.log(`Hello there, ${data.blue_player}`);
}
}
See mapped types in the docs for more examples and a drill down.