From 43c3cfdec5ae5d70fa2a21e857abc2d73f1a0d07 Mon Sep 17 00:00:00 2001 From: Carlos Rodrigues Date: Sun, 3 Dec 2023 23:59:01 +0000 Subject: [PATCH] fix(types): improve return type withKeys and withModifiers (#9734) --- packages/dts-test/defineComponent.test-d.tsx | 10 +++++++++- packages/runtime-dom/src/directives/vOn.ts | 18 ++++++++++-------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/dts-test/defineComponent.test-d.tsx b/packages/dts-test/defineComponent.test-d.tsx index b3f735ddad9..9c989c23b24 100644 --- a/packages/dts-test/defineComponent.test-d.tsx +++ b/packages/dts-test/defineComponent.test-d.tsx @@ -11,7 +11,9 @@ import { h, SlotsType, Slots, - VNode + VNode, + withKeys, + withModifiers } from 'vue' import { describe, expectType, IsUnion } from './utils' @@ -1497,6 +1499,12 @@ describe('should work when props type is incompatible with setup returned type ' expectType(CompA.$props.size) }) +describe('withKeys and withModifiers as pro', () => { + const onKeydown = withKeys(e => {}, ['']) + const onClick = withModifiers(e => {}, ['']) + ; +}) + import { DefineComponent, ComponentOptionsMixin, diff --git a/packages/runtime-dom/src/directives/vOn.ts b/packages/runtime-dom/src/directives/vOn.ts index b1f4492e0ac..8054efb9ea5 100644 --- a/packages/runtime-dom/src/directives/vOn.ts +++ b/packages/runtime-dom/src/directives/vOn.ts @@ -32,19 +32,21 @@ const modifierGuards: Record< /** * @private */ -export const withModifiers = ( - fn: Function & { _withMods?: Function }, +export const withModifiers = < + T extends (event: Event, ...args: unknown[]) => any +>( + fn: T & { _withMods?: T }, modifiers: string[] ) => { return ( fn._withMods || - (fn._withMods = (event: Event, ...args: unknown[]) => { + (fn._withMods = ((event, ...args) => { for (let i = 0; i < modifiers.length; i++) { const guard = modifierGuards[modifiers[i]] if (guard && guard(event, modifiers)) return } return fn(event, ...args) - }) + }) as T) ) } @@ -63,8 +65,8 @@ const keyNames: Record = { /** * @private */ -export const withKeys = ( - fn: Function & { _withKeys?: Function }, +export const withKeys = any>( + fn: T & { _withKeys?: T }, modifiers: string[] ) => { let globalKeyCodes: LegacyConfig['keyCodes'] @@ -88,7 +90,7 @@ export const withKeys = ( return ( fn._withKeys || - (fn._withKeys = (event: KeyboardEvent) => { + (fn._withKeys = (event => { if (!('key' in event)) { return } @@ -123,6 +125,6 @@ export const withKeys = ( } } } - }) + }) as T) ) }