Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Composition API - getting a ref using TypeScript

Vetur is underlining null on this line below:

const firstRef = ref<HTMLElement>(null)
No overload matches this call.
 Overload 1 of 3, '(raw: HTMLElement): Ref', gave the following error.
  Argument of type 'null' is not assignable to parameter of type 'HTMLElement'.
 Overload 2 of 3, '(raw: HTMLElement): Ref', gave the following error.
  Argument of type 'null' is not assignable to parameter of type 'HTMLElement'.Vetur(2769)

Here's a condensed context. Any ideas what I did wrong?

<template>
  <input id="first" ref="firstRef">
  <button type="button" @click.prevent="focusFirst">Focus</button>
</template>

<script lang="ts">
import { defineComponent, ref } from "@vue/composition-api"
export default defineComponent({
  name: "Test",
  setup() {
    const firstRef = ref<HTMLElement>(null)
    const focusFirst = () => {
      const theField = firstRef.value
      theField.focus()
    }

    return { focusFirst }
  }
</script>
like image 963
nstuyvesant Avatar asked Jul 21 '20 20:07

nstuyvesant


People also ask

How to use typescript in Vue app?

Now go to App.vue and tell the script section to use TypeScript adding lang="ts", import createComponent and ref from @vue/composition-api and our interface and service:

How do I make use of the typescript API?

To make use of the API we need to declare and use the createComponent we extracted from the API and establish the export default with the createComponent to make use of TypeScript. After that we can now use the setup method to prepare and fetch out data from the service, so we can now do this:

How to get data from an API in Vue devtool?

As we can see to make a ref as a type just add <TypeHere> and your variable will be set as the desired type, make an async/await function to fetch our data, call it before the return and with this we can retrieve any information we need from an API, you can go to your Vue DevTool and check yourself we gathered the data.

Why does typescript fail to infer the type of a function?

Because of a design limitation in TypeScript, you have to be careful when using function values for validator and default prop options - make sure to use arrow functions: This prevents TypeScript from having to infer the type of this inside these functions, which, unfortunately, can cause the type inference to fail.


1 Answers

As given back by Vetur, you cannot convert a null type to an HTMLELement type. A possible way to fix this would be to write:

const firstRef = ref<HTMLElement | null>(null)

However, keep in mind that you'll have to check if firstRef is of type null every time you want to use it. You could do something like this as well:

if (firstRef.value) {
  // do stuff with firstRef
  // typescript knows that it must be of type HTMLElement here.
}
like image 126
Keimeno Avatar answered Sep 24 '22 12:09

Keimeno