فهرست منبع

feat(types): improve event type inference when using `h` with native elements (#9756)

丶远方 2 سال پیش
والد
کامیت
a625376ac8
2فایلهای تغییر یافته به همراه29 افزوده شده و 1 حذف شده
  1. 12 1
      packages/dts-test/h.test-d.ts
  2. 17 0
      packages/runtime-core/src/h.ts

+ 12 - 1
packages/dts-test/h.test-d.ts

@@ -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', () => {

+ 17 - 0
packages/runtime-core/src/h.ts

@@ -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,