Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strongly typed event names & values #106

Closed
franky47 opened this issue Jun 17, 2020 · 5 comments · Fixed by #114
Closed

Strongly typed event names & values #106

franky47 opened this issue Jun 17, 2020 · 5 comments · Fixed by #114
Labels

Comments

@franky47
Copy link

I really like mitt, and the rewrite in TypeScript is a great step forward, but I wonder if we could go a bit further and allow strong typing of both the event names and their associated values.

Ideally, this would be an opt-in behaviour, meaning that by default mitt uses a string | symbol type for event names, and any for values. But passing an interface as a generic type to the constructor would tell mitt what events to expect and what values are associated, along with providing auto-completion in IDEs.

Hypothetical API:

interface MittEvents
{
  foo: number
  bar: string
  egg: {
    a: string[]
    b?: number
  }
  noarg: null
}

const emitter = mitt<MittEvents>()

emitter.on('foo', value => {
  // value has type `number`
})

emitter.on('bar', value => {
  // value has type `string`
})

emitter.on('egg', ({ a, b = 0 }) => {
  // a has type `string[]`
  // b has type `number` with a default value
})

emitter.emit('foo', 42)
emitter.emit('noarg', null)

// Check value type
emitter.emit('foo', 'not a number') // <- TS error

// Check allowed event names
emitter.emit('another', 42) // <- TS error

Such a typing system can be seen in action in vegemite, a state management library with a similar EventEmitter interface.

@developit
Copy link
Owner

@franky47 I like the idea! Curious how we could do this given the move to Map though.

@ZeroThe2nd
Copy link

Is this still being planned for implementation, or will this be dropped altogether in its current state?

@franky47
Copy link
Author

franky47 commented Feb 1, 2021

PR #114 is exactly what I'm looking for, FYI.

@ZeroThe2nd
Copy link

@franky47 It'll need to be approved first though. It would be a nice addition for sure.

@danielweck
Copy link

This TypeScript userland solution (outside of Mitt) works perfectly fine:
#112 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants