Skip to content

Commit

Permalink
Add type for conveniently typing mixin objects
Browse files Browse the repository at this point in the history
  • Loading branch information
fuadsaud committed Oct 12, 2024
1 parent dddd03b commit d969c68
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
24 changes: 24 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,27 @@ export interface Emitter<Events extends EventsMap = DefaultEvents> {
export function createNanoEvents<
Events extends EventsMap = DefaultEvents
>(): Emitter<Events>

/**
* An interface for mixins that expose the `on` function (without the emitter
* bound to `this`)
*
* ```js
* import { createNanoEvents } from 'nanoevents'
*
* class Ticker implements EmitterMixin<Events> {
* constructor() {
* this.emitter = createNanoEvents()
* }
* on(...args) {
* return this.emitter.on(...args)
* }
* tick() {
* this.emitter.emit('tick')
* }
* }
* ```
*/
export interface EmitterMixin<Events extends EventsMap = DefaultEvents> {
on<K extends keyof Events>(event: K, cb: Events[K]): Unsubscribe
}
25 changes: 24 additions & 1 deletion test/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Emitter } from '../index.js';
import type { Emitter, EmitterMixin } from '../index.js';
import { createNanoEvents } from '../index.js'

interface Events {
Expand Down Expand Up @@ -37,3 +37,26 @@ function listenersCount(emitter: Emitter): number {
}

console.log(listenersCount(ee))

type Mixin = {
add: () => void
} & EmitterMixin<Events>

const createMixin = (): Mixin => {
let mixinEmitter = createNanoEvents<Events>()

return {
add: () => {
mixinEmitter.emit('add', 1)
},
on: mixinEmitter.on.bind(mixinEmitter),
}
}

const mixin = createMixin()

mixin.on('add', (a) => {
console.log(a)
})

mixin.add()

0 comments on commit d969c68

Please sign in to comment.