#Need help designing generic function

4 messages · Page 1 of 1 (latest)

sonic prawn
#

Hi,

so I have a function like this

function makeListener(event, fn) {}

then I call it like ```js
makeListener("OpenContainer", (event) => {

})


and I have a .d.ts that has a `declare namespace Events {`
that has a `interface OpenContainer extends BaseEvent {`

So, I'd like to make event's type OpenContainer, how would I go about doing that?
#

I guess I'd also like the event param in makeListener to be typechecked so it has to be one of the interfaces in Events

quaint ridge
#

you need to create a type mapping the event names to event types, then use it to define the signature of makeListener:

fathom hawkBOT
#
mkantor#7432

Preview:```ts
namespace Events {
export interface OpenContainer {
isOpenContainerEvent: true
}
export interface SomeOtherEvent {
isSomeOtherEvent: true
}
}

type EventsByName = {
OpenContainer: Events.OpenContainer
SomeOtherEvent: Events.SomeOtherEvent
...```