Introduction
A half a year has already passed since I wrote the Vue.js Typed events article. During all this time I was searching for a solution, which doesn't require from a developer to change the way how one is used to emit events in Vue.js components (this.$emit('event', payload)). Finally I've found one, and that's resulted in vue-typed-emit library creation.
Features
The main feature of the library is that it doesn't require from a developer any typed wrappers over a this.$emit invocation. It only requires a simple type which describes names of events your component is supposed to emit along with corresponding payloads.
Here is a trivial example:
import Vue from 'vue'
import { WithEvents } from 'vue-typed-emit'
interface Events {
foo: string
bar: [string, number]
baz: undefined
}
export default (Vue as WithEvents<Events>).extend({
name: 'Component',
methods: {
method() {
this.$emit('foo', 'foo')
this.$emit('bar', 0)
this.$emit('baz')
},
},
})
vue-typed-emit verifies that component emits only declared events with valid payloads.
If a developer tries to emit invalid event or invalid payload, one gets an error from TypeScript.
You can find vue-type-refs on GitHub and NPM. Feel free to contribute.


Top comments (1)
Hey! Thanks for the article, nice solution.
What do you think about new
emitsproperty? It allows you to type hint emits when using with TS. For example:Further reading:
v3.vuejs.org/api/options-data.html...
github.com/vuejs/rfcs/blob/master/...