Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Dec 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/dts-test/defineComponent.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import {
h,
SlotsType,
Slots,
VNode
VNode,
withKeys,
withModifiers
} from 'vue'
import { describe, expectType, IsUnion } from './utils'

Expand Down Expand Up @@ -1497,6 +1499,12 @@ describe('should work when props type is incompatible with setup returned type '
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 {
DefineComponent,
ComponentOptionsMixin,
Expand Down
18 changes: 10 additions & 8 deletions packages/runtime-dom/src/directives/vOn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
}

Expand All @@ -63,8 +65,8 @@ const keyNames: Record<string, string | string[]> = {
/**
* @private
*/
export const withKeys = (
fn: Function & { _withKeys?: Function },
export const withKeys = <T extends (event: KeyboardEvent) => any>(
fn: T & { _withKeys?: T },
modifiers: string[]
) => {
let globalKeyCodes: LegacyConfig['keyCodes']
Expand All @@ -88,7 +90,7 @@ export const withKeys = (

return (
fn._withKeys ||
(fn._withKeys = (event: KeyboardEvent) => {
(fn._withKeys = (event => {
if (!('key' in event)) {
return
}
Expand Down Expand Up @@ -123,6 +125,6 @@ export const withKeys = (
}
}
}
})
}) as T)
)
}