Skip to content

Commit

Permalink
fix: Event listener callback type
Browse files Browse the repository at this point in the history
Also use strong key types everywhere
  • Loading branch information
franky47 committed May 10, 2020
1 parent 2a9e14c commit bb4302e
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,23 @@ const convertV0toV1 = (v0Entry: ExpirableKeyV0): ExpirableKeyV1 => ({

// --

export interface KeyEvent {
name: string
export interface KeyEvent<Keys> {
name: Keys
}

export interface EventMap {
created: KeyEvent
read: KeyEvent
updated: KeyEvent
deleted: KeyEvent
expired: KeyEvent
export interface EventMap<Keys> {
created: KeyEvent<Keys>
read: KeyEvent<Keys>
updated: KeyEvent<Keys>
deleted: KeyEvent<Keys>
expired: KeyEvent<Keys>
}

export type EventTypes = keyof EventMap
export type EventPayload<T extends EventTypes> = EventMap[T]
export type Callback<T extends EventTypes> = (value: T) => void
export type EventTypes<Keys> = keyof EventMap<Keys>
export type EventPayload<Keys, T extends EventTypes<Keys>> = EventMap<Keys>[T]
export type Callback<Keys, T extends EventTypes<Keys>> = (
value: EventPayload<Keys, T>
) => void

export interface ConstructorOptions {
name?: string
Expand Down Expand Up @@ -77,12 +79,12 @@ export default class SessionKeystore<Keys = string> {
// Event Emitter --

// Returns an unsubscribe callback
on<T extends EventTypes>(event: T, callback: Callback<T>) {
on<T extends EventTypes<Keys>>(event: T, callback: Callback<Keys, T>) {
this.#emitter.on(event, callback)
return () => this.#emitter.off(event, callback)
}

off<T extends EventTypes>(event: T, callback: Callback<T>) {
off<T extends EventTypes<Keys>>(event: T, callback: Callback<Keys, T>) {
this.#emitter.off(event, callback)
}

Expand Down

0 comments on commit bb4302e

Please sign in to comment.