Soviut
Soviut

Reputation: 91525

What type is a Vue 3 template function ref?

Vue 3 allows a function to be used to assign a ref

const target = ref<Element>()

const functionRef = (ref: Element) => {
  target.value = ref
}
<template>
  <div :ref="functionRef" />
</template>

However, Volar and TypeScript will both complain that the :ref="functionRef" binding has a type mismatch.

Type '(ref: Element) => void' is not assignable to type 'string | Ref | ((ref: Element | ComponentPublicInstance<{}, {}, {}, {}, {}, {}, {}, {}, false, ComponentOptionsBase<any, any, any, any, any, any, any, any, any, {}>> | null) => void) | undefined'.

runtime-dom.d.ts(1479, 3): The expected type comes from property 'ref' which is declared here on type 'ElementAttrs'

What is the type of a function ref?

Upvotes: 1

Views: 3044

Answers (2)

Soviut
Soviut

Reputation: 91525

The runtime-dom.d.ts link contains the following definition.

type ReservedProps = {
  key?: string | number | symbol
  ref?:
    | string
    | RuntimeCore.Ref
    | ((ref: Element | RuntimeCore.ComponentPublicInstance | null) => void)
  ref_for?: boolean
  ref_key?: string
}

This definition can be found in the source here.

The important part is third union type for ref?

(ref: Element | RuntimeCore.ComponentPublicInstance | null) => void

This means you can define a reusable type for the ref argument as follows.

// this may not be necessary depending on where you put this definition
import * as RuntimeCore from '@vue/runtime-core'

type VueRef = (ref: Element | RuntimeCore.ComponentPublicInstance | null) => void

You can now update your function ref with the new type for the arg

const target = ref<Element>()

const functionRef = (ref: VueRef) => {
  target.value = ref
}

Upvotes: 2

Gephrey Chen
Gephrey Chen

Reputation: 41

import { ComponentPublicInstance } from 'vue';
const functionRef = (ref: ComponentPublicInstance | null | Element) => {
  target.value = ref
}
<div :ref="functionRef" />

Upvotes: 3

Related Questions