Exploring TypeScript to get a ref with the Vue Composition API

The issue I'm facing is related to Vetur underlining 'null' in the following line:

const firstRef = ref<HTMLElement>(null)
<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>

Answer №1

According to Vetur's feedback, converting a null type to an HTMLElement type is not possible. One way to resolve this issue is by initializing the reference like this:

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

Nevertheless, it is important to note that you will need to verify if firstRef is of type null before using it. You can also handle it in the following manner:

if (firstRef.value) {
  // perform operations with firstRef
  // TypeScript ensures it is an HTMLElement type at this point.
}

Answer №2

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

Attempting to access HTML properties, as well as Vue component methods and props, using the above code snippet can lead to errors. It is advisable to utilize the following syntax instead:

const myComponentRef = ref<InstanceType<typeof MyComponent>>()

Source: Enhancing typing for component references

Answer №3

One alternative method to consider is using optional chaining, which has been available since TypeScript 3.7:

firstRef.value?.focus()

This approach is suitable for TypeScript and will only run the command if firstRef.value is not null or undefined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge: I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core p ...

Adjust the component suppliers based on the @input

If I were to implement a material datepicker with a selection strategy, I would refer to this example There are instances where the selection strategy should not be used. The challenge lies in setting the selection strategy conditionally when it is insta ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

What is the best way to include a non-Typed Angular service in a TypeScript class?

I have a module and service in Angular that were originally developed without TypeScript, like this: MyModule = angular.module('MyModule', ['dependency1', 'dependency2']); MyModule.factory('MyService', ['$other ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

What could be causing the lack of reactivity in the body object during the sending of a POST API

Utilizing Vercel's AI SDK along with the useChat utility hook from Vercel in my Nuxt.js project, I'm developing a chat interface. Within this interface, I have multiple agents (such as General, Exercise, Cardiology) listed in a select dropdown me ...

The ultimate guide to handling arrays in Vue: tackling the v-model dilemma

Just getting started with Vue and I've been attempting to modify an array of strings using the v-model property. I put together a small JSFiddle where I'm encountering issues with editing the array. An error message appears suggesting that I shou ...

Deploying Vue.js applications

I am working on a Vue application that was created using vue-cli. It is semi-developed and I would like to show the progress to a customer. Therefore, I am looking to deploy what we have so far. If I execute the script npm run build, will I still be able ...

Passing a boolean value from the parent Stepper component to a child step in Angular

I am facing an issue with passing the boolean value isNewProposal from a parent Angular Material stepper component to its children steps. Despite using @Input(), the boolean remains undefined in the child component, even after being assigned a value (true ...

Getting data from an Array using Axios in Laravel

After making an Axios request to one of my controller functions, it retrieves all the suppliers' information from the database. However, when this data is returned to my VUE file, there seems to be no data present. Here is the Axios request: mounted ...

Retrieve the $root instance in Vuex actions

I have a Loader component that is triggered to execute based on certain conditions. created() { this.$root.$on('show-loading', (vars) => { this.loading = vars; console.log('loader executed'); }); }, Currently ...

Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a func ...

Refine specific unions by considering past values that have been used

Here's the scenario at hand: type Option = 'x' | 'y' | 'z' | 'w' type Inquiry = { query: string; choices: Option[]; defaultChoice: Option // here's where it gets tricky } I am looking to set the def ...

What is the function of the # symbol within a <template> in the context of v-data-table in Vue JS?

I recently started learning Vue.js and was given a project example to review. Can someone please explain what the code <template #['item.amtv_start_sales_date'] = "{item}"> actually does in this context? Any help would be greatly appreciate ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

``What is the best approach for specifying property types when passing props to grandchildren within a Vue.js component hierarchy

I have a Vue component named foo embedded in my HTML, and I am passing a parameter to it as shown below: <foo some="Some String"></foo> Within the foo component, I define the property type and default value in the following manner: export d ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

Is there a way to access and invoke a exposed function of a Vue component within a default slot?

Exploring the realms of a vue playground. The functions interfaceFunction in both ChildA and ChildB are exposed. In App, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from with ...

Having trouble retrieving an Enum within an Angular template?

I am trying to use an enum to read a property of an array. However, I encountered an error with the following code: <ng-container *ngFor="let elem of list"> <div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-12 ui-xl-12"> &l ...