8000 fix(createEventHook): make createEventHook union type can be inferred… · vueuse/vueuse@e48ca07 · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Commit e48ca07

Browse files
authored
fix(createEventHook): make createEventHook union type can be inferred correctly (#3569)
1 parent fd67ba3 commit e48ca07

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

packages/shared/createEventHook/index.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,19 @@ describe('createEventHook', () => {
9393
expect(result).toEqual([2])
9494
})
9595

96+
it('should pass union type', () => {
97+
let count = 0
98+
99+
const { on: onResult, trigger } = createEventHook<number | string>()
100+
101+
// union type should be inferred
102+
onResult(value => count = 2)
103+
trigger(1)
104+
trigger(2)
105+
106+
expect(count).toBe(2)
107+
})
108+
96109
it('the same listener should fire only once', () => {
97110
const listener = vi.fn()
98111
const { on, trigger, off } = createEventHook<string>()

packages/shared/createEventHook/index.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,19 @@
22
* The source code for this function was inspired by vue-apollo's `useEventHook` util
33
* https://github.com/vuejs/vue-apollo/blob/v4/packages/vue-apollo-composable/src/util/useEventHook.ts
44
*/
5+
import type { IsAny } from '../utils/types'
56
import { tryOnScopeDispose } from '../tryOnScopeDispose'
67

7-
type Callback<T> = T extends void ? () => void : (param: T) => void
8+
// any extends void = true
9+
// so we need to check if T is any first
10+
type Callback<T> = IsAny<T> extends true
11+
? (param: any) => void
12+
: (
13+
[T] extends [void]
14+
? () => void
15+
: (param: T) => void
16+
)
17+
818
export type EventHookOn<T = any> = (fn: Callback<T>) => { off: () => void }
919
export type EventHookOff<T = any> = (fn: Callback<T>) => void
1020
export type EventHookTrigger<T = any> = (param?: T) => Promise<unknown[]>

packages/shared/utils/types.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,3 +148,10 @@ export type MapOldSources<T, Immediate> = {
148148
}
149149

150150
export type Mutable<T> = { -readonly [P in keyof T]: T[P] }
151+
152+
// https://stackoverflow.com/questions/55541275/typescript-check-for-the-any-type
153+
export type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N
154+
/**
155+
* will return `true` if `T` is `any`, or `false` otherwise
156+
*/
157+
export type IsAny<T> = IfAny<T, true, false>

0 commit comments

Comments
 (0)
0