fix(types): improve return type withKeys and withModifiers (#9734)

This commit is contained in:
Carlos Rodrigues 2023-12-03 23:59:01 +00:00 committed by GitHub
parent 9ea2b868be
commit 43c3cfdec5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 9 deletions

View File

@ -11,7 +11,9 @@ import {
h, h,
SlotsType, SlotsType,
Slots, Slots,
VNode VNode,
withKeys,
withModifiers
} from 'vue' } from 'vue'
import { describe, expectType, IsUnion } from './utils' import { describe, expectType, IsUnion } from './utils'
@ -1497,6 +1499,12 @@ describe('should work when props type is incompatible with setup returned type '
expectType<SizeType>(CompA.$props.size) expectType<SizeType>(CompA.$props.size)
}) })
describe('withKeys and withModifiers as pro', () => {
const onKeydown = withKeys(e => {}, [''])
const onClick = withModifiers(e => {}, [''])
;<input onKeydown={onKeydown} onClick={onClick} />
})
import { import {
DefineComponent, DefineComponent,
ComponentOptionsMixin, ComponentOptionsMixin,

View File

@ -32,19 +32,21 @@ const modifierGuards: Record<
/** /**
* @private * @private
*/ */
export const withModifiers = ( export const withModifiers = <
fn: Function & { _withMods?: Function }, T extends (event: Event, ...args: unknown[]) => any
>(
fn: T & { _withMods?: T },
modifiers: string[] modifiers: string[]
) => { ) => {
return ( return (
fn._withMods || fn._withMods ||
(fn._withMods = (event: Event, ...args: unknown[]) => { (fn._withMods = ((event, ...args) => {
for (let i = 0; i < modifiers.length; i++) { for (let i = 0; i < modifiers.length; i++) {
const guard = modifierGuards[modifiers[i]] const guard = modifierGuards[modifiers[i]]
if (guard && guard(event, modifiers)) return if (guard && guard(event, modifiers)) return
} }
return fn(event, ...args) return fn(event, ...args)
}) }) as T)
) )
} }
@ -63,8 +65,8 @@ const keyNames: Record<string, string | string[]> = {
/** /**
* @private * @private
*/ */
export const withKeys = ( export const withKeys = <T extends (event: KeyboardEvent) => any>(
fn: Function & { _withKeys?: Function }, fn: T & { _withKeys?: T },
modifiers: string[] modifiers: string[]
) => { ) => {
let globalKeyCodes: LegacyConfig['keyCodes'] let globalKeyCodes: LegacyConfig['keyCodes']
@ -88,7 +90,7 @@ export const withKeys = (
return ( return (
fn._withKeys || fn._withKeys ||
(fn._withKeys = (event: KeyboardEvent) => { (fn._withKeys = (event => {
if (!('key' in event)) { if (!('key' in event)) {
return return
} }
@ -123,6 +125,6 @@ export const withKeys = (
} }
} }
} }
}) }) as T)
) )
} }