File tree Expand file tree Collapse file tree 3 files changed +31
-1
lines changed Expand file tree Collapse file tree 3 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -93,6 +93,19 @@ describe('createEventHook', () => {
93
93
expect ( result ) . toEqual ( [ 2 ] )
94
94
} )
95
95
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
+
96
109
it ( 'the same listener should fire only once' , ( ) => {
97
110
const listener = vi . fn ( )
98
111
const { on, trigger, off } = createEventHook < string > ( )
Original file line number Diff line number Diff line change 2
2
* The source code for this function was inspired by vue-apollo's `useEventHook` util
3
3
* https://github.com/vuejs/vue-apollo/blob/v4/packages/vue-apollo-composable/src/util/useEventHook.ts
4
4
*/
5
+ import type { IsAny } from '../utils/types'
5
6
import { tryOnScopeDispose } from '../tryOnScopeDispose'
6
7
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
+
8
18
export type EventHookOn < T = any > = ( fn : Callback < T > ) => { off : ( ) => void }
9
19
export type EventHookOff < T = any > = ( fn : Callback < T > ) => void
10
20
export type EventHookTrigger < T = any > = ( param ?: T ) => Promise < unknown [ ] >
Original file line number Diff line number Diff line change @@ -148,3 +148,10 @@ export type MapOldSources<T, Immediate> = {
148
148
}
149
149
150
150
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 >
You can’t perform that action at this time.
0 commit comments