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
  • Loading branch information
Doctor-wu committed Nov 28, 2023
1 parent 8ba4df8 commit 1609e94
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
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
2 changes: 1 addition & 1 deletion packages/shared/createEventHook/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/
import { tryOnScopeDispose } from '../tryOnScopeDispose'

type Callback<T> = T extends void ? () => void : (param: T) => void
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 EventHookTrigger<T = any> = (param?: T) => Promise<unknown[]>
Expand Down

0 comments on commit 1609e94

Please sign in to comment.