Browse Source

fix(types): support Ref and function types in tsx ref attribute (#12759)

fix #12758
Shiluo34 3 years ago
parent
commit
87f69aa26f
2 changed files with 17 additions and 2 deletions
  1. 6 1
      types/test/v3/tsx-test.tsx
  2. 11 1
      types/vnode.d.ts

+ 6 - 1
types/test/v3/tsx-test.tsx

@@ -1,4 +1,4 @@
-import { VNode, defineComponent } from '../../index'
+import { VNode, defineComponent, ref } from '../../index'
 import { expectType } from '../utils'
 
 expectType<VNode>(<div />)
@@ -22,6 +22,11 @@ expectError(<div foo="bar" />)
 expectType<JSX.Element>(<div key="foo" />)
 expectType<JSX.Element>(<div ref="bar" />)
 
+// allow Ref type type on arbitrary element
+const fooRef = ref<HTMLElement>()
+expectType<JSX.Element>(<div ref={fooRef} />)
+expectType<JSX.Element>(<div ref={(el) => {fooRef.value = el as HTMLElement}} />)
+
 expectType<JSX.Element>(
   <input
     onInput={e => {

+ 11 - 1
types/vnode.d.ts

@@ -1,5 +1,7 @@
 import { Vue } from './vue'
 import { DirectiveFunction, DirectiveOptions } from './options'
+import { Ref } from './v3-generated'
+import { ComponentPublicInstance } from './v3-component-public-instance'
 
 /**
  * For extending allowed non-declared props on components in TSX
@@ -65,11 +67,19 @@ export interface VNodeComponentOptions {
   tag?: string
 }
 
+export type VNodeRef =
+  | string
+  | Ref
+  | ((
+      ref: Element | ComponentPublicInstance | null,
+      refs: Record<string, any>
+    ) => void)
+
 export interface VNodeData {
   key?: string | number
   slot?: string
   scopedSlots?: { [key: string]: ScopedSlot | undefined }
-  ref?: string
+  ref?: VNodeRef
   refInFor?: boolean
   tag?: string
   staticClass?: string