Home > front end >  How to define type of a callback input that depends on the inputted event name
How to define type of a callback input that depends on the inputted event name

Time:04-29

For example if I had something like:

type eventType = "ready" | "buzz";
type eventTypeReadyInput = {appIsReady: string};
interface mysdk {
  on:(event: eventType, cb: (input: eventTypeCallbackInput) => void) => void
}
mysdk.on("ready", (readyInput) => {})

How can I make it so that ready input is typed based on the eventType instead of having to declare it like this:

mysdk.on("ready", (readyInput: eventTypeReadyInput) => {});

Hope that makes sense.

CodePudding user response:

You can have a lookup Mapping type, that gives us a relationship between each of the Event type, and it's corresponding input And then using generic function you can conditionally type the event and it's callback input.

type eventType = "ready" | "buzz";
type eventTypeReadyInput = {appIsReady: string};
type eventTypeBuzzInput = {appIsBuzzing: string};

type EventLookup =  {
    "ready": eventTypeReadyInput,
    "buzz": eventTypeBuzzInput
}


interface SDK {
  on:<EType extends keyof EventLookup>(event: EType, cb: (input: EventLookup[EType]) => void) => void
}

declare let mysdk: SDK;

mysdk.on("ready", (readyInput) => { readyInput.appIsReady })
mysdk.on("buzz", (readyInput) => { readyInput.appIsBuzzing })

Code Playground

  • Related