]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(types): improve event type inference when using `h` with native elements (...
author丶远方 <yangpanteng@gmail.com>
Mon, 11 Dec 2023 14:10:01 +0000 (22:10 +0800)
committerGitHub <noreply@github.com>
Mon, 11 Dec 2023 14:10:01 +0000 (22:10 +0800)
packages/dts-test/h.test-d.ts
packages/runtime-core/src/h.ts

index f2e984b49b8d4faf939a543edefd9415c8ebeab5..2392c5850f11abe7f7b0b93b83e328e1f027a0a8 100644 (file)
@@ -9,7 +9,7 @@ import {
   Component,
   resolveComponent
 } from 'vue'
-import { describe, expectAssignable } from './utils'
+import { describe, expectAssignable, expectType } from './utils'
 
 describe('h inference w/ element', () => {
   // key
@@ -32,6 +32,17 @@ describe('h inference w/ element', () => {
   // slots
   const slots = { default: () => {} } // RawSlots
   h('div', {}, slots)
+  // events
+  h('div', {
+    onClick: e => {
+      expectType<MouseEvent>(e)
+    }
+  })
+  h('input', {
+    onFocus(e) {
+      expectType<FocusEvent>(e)
+    }
+  })
 })
 
 describe('h inference w/ Fragment', () => {
index 4ca90262f2a95dcf445b472766f3af5df5cc0e54..038d8d2fbc70afadac79afe9d698187f5708bf13 100644 (file)
@@ -75,10 +75,27 @@ interface Constructor<P = any> {
   new (...args: any[]): { $props: P }
 }
 
+type HTMLElementEventHandler = {
+  [K in keyof HTMLElementEventMap as `on${Capitalize<K>}`]?: (
+    ev: HTMLElementEventMap[K]
+  ) => any
+}
+
 // The following is a series of overloads for providing props validation of
 // manually written render functions.
 
 // element
+export function h<K extends keyof HTMLElementTagNameMap>(
+  type: K,
+  children?: RawChildren
+): VNode
+export function h<K extends keyof HTMLElementTagNameMap>(
+  type: K,
+  props?: (RawProps & HTMLElementEventHandler) | null,
+  children?: RawChildren | RawSlots
+): VNode
+
+// custom element
 export function h(type: string, children?: RawChildren): VNode
 export function h(
   type: string,