Skip to content

Commit

Permalink
fix(createEventHook): make createEventHook union type can be inferred…
Browse files Browse the repository at this point in the history
… correctly

fix #3565
  • Loading branch information
Doctor-wu committed Nov 19, 2023
1 parent 8ba4df8 commit b0ce7bb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
13 changes: 13 additions & 0 deletions packages/shared/createEventHook/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,19 @@ describe('createEventHook', () => {
expect(result).toEqual([2])
})

it('should pass union type', () => {
let count = 0

const { on: onResult, trigger } = createEventHook<number | string>()

// union type should be inferred
onResult(value => count = 2)
trigger(1)
trigger(2)

expect(count).toBe(2)
})

it('the same listener should fire only once', () => {
const listener = vi.fn()
const { on, trigger, off } = createEventHook<string>()
Expand Down
10 changes: 5 additions & 5 deletions packages/shared/createEventHook/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import { tryOnScopeDispose } from '../tryOnScopeDispose'

type Callback<T> = T extends void ? () => void : (param: T) => void
export type EventHookOn<T = any> = (fn: Callback<T>) => { off: () => void }
export type EventHookOff<T = any> = (fn: Callback<T>) => void
export type EventHookOn<T = any> = (fn: (param: T) => void) => { off: () => void }
export type EventHookOff<T = any> = (fn: (param: T) => void) => void
export type EventHookTrigger<T = any> = (param?: T) => Promise<unknown[]>

export interface EventHook<T = any> {
Expand All @@ -21,13 +21,13 @@ export interface EventHook<T = any> {
* @see https://vueuse.org/createEventHook
*/
export function createEventHook<T = any>(): EventHook<T> {
const fns: Set<Callback<T>> = new Set()
const fns: Set<(param: T) => void> = new Set()

const off = (fn: Callback<T>) => {
const off = (fn: (param: T) => void) => {
fns.delete(fn)
}

const on = (fn: Callback<T>) => {
const on = (fn: (param: T) => void) => {
fns.add(fn)
const offFn = () => off(fn)

Expand Down

0 comments on commit b0ce7bb

Please sign in to comment.