A guide on implementing Vue 3 Composition API (Typescript) to store user-inputted values in an array

I'm currently working on creating a simple todo list app using the Vue 3 Composition API along with Typescript. I've set up the submit function in the form to trigger the addTodo() method within the setup function. The goal is to add user-inputted values to the listItems array, which I initialized using the ref method. In my addTodo() function, I included

listItems.value.push(newTodo.value)
to append the input value to the array. However, I'm encountering an error related to the newTodo.value parameter, specifically stating
Argument of type 'string' is not assignable to parameter of type 'never'
. As I am relatively new to the Composition API in Vue 3, I would appreciate guidance on how to address this type error.

Please find below the code snippet:

Template

<template>
  <div class="container">
      <form @submit.prevent="addTodo()">
          <label>New ToDo</label>
          <input
              v-model="newTodo"
              name="newTodo"
              autocomplete="off"
          >
          <button>Add ToDo</button>
      </form>

    <div class="content">
      <ul>
        <li v-for="listItem in listItems" :key="listItem">
          <h3>{{ listItem }}</h3>
        </li>
      </ul>
    </div>
  </div>
</template>

Script

<script lang="ts">
import { defineComponent, ref } from 'vue';

export default defineComponent({
  name: 'Form',
  
  setup() {
    const newTodo = ref('');
    const listItems = ref([]);

    const addTodo = () => {
      listItems.value.push(newTodo.value)
      newTodo.value = ''
    }
    
    return { newTodo, listItems, addTodo }
  }
});
</script>

Answer №1

To properly type listItems, you must declare it like this:

const listItems = ref<string[]>([]);

Without this declaration, TypeScript will not be able to determine the type of array that listItems is.

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

The function startAfter() in Firebase Realtime Database (RTDB) does not seem

I'm currently implementing pagination for a list of items using Vuefire, and encountering an error with the following code snippet (the function works properly with startAt() but not with startAfter()) lastVisible is an object within my component&apo ...

Load Vue: Include jQuery globally for all components

When working with vue-loader single file components, I often need to use jQuery in specific components. To do this, I typically import jQuery like so: import $ from 'jQuery' Is there a way to import jQuery globally, making it available for all ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...

Testing Next.js's getServerSideProps function with Jest: A Step-by-Step Guide

I want to conduct Jest and Enzyme tests on the Next.js getServerSideProps function. This function is structured as follows: export const getServerSideProps: GetServerSideProps = async (context) => { const id = context?.params?.id; const businessName ...

Arranging List Alphabetically in Nested v-for with Vue 3

Currently, I am attempting to organize the following v-for list in alphabetical order (A-Z). I am familiar with a computed property method that is used for sorting v-for lists alphabetically; sortedList() { const res = [] this.itemt ...

Troubleshooting problems encountered in Nest.js due to modifications made within a service.ts file

I'm currently working on a Nest.js project and here is the content of the automobile.service.ts file: import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Car } from './enti ...

The 'data' property is absent in the 'never[]' type, whereas it is necessary in the type of product data

Hello, I am new to TypeScript and I'm struggling with fixing this error message: Property 'data' is missing in type 'never[]' but required in type '{ data: { products: []; }; }'. Here is my code snippet: let medias :[] ...

Adding properties to a class object in Javascript that are integral to the class

Recently, I've been contemplating the feasibility of achieving a certain task in JavaScript. Given my limited experience in the realm of JavaScript, I appreciate your patience as I navigate through this. To illustrate what I am aiming for, here' ...

JavaScript - Cannot access the 'name' property on an empty object

I am currently following a React tutorial that demonstrates how to create a useForm hook for linking form input to state. Here is the implementation of the hook: const useForm = (initial = {}) => { const [inputs, setInputs] = useState(initial) ...

Failure of props to synchronize with parent instance information

I'm currently facing an issue with my "Product" component where the data from the parent is not being passed to the child. It seems to be stuck at the default value entered in the main template. The shipping cost should be either free or $2.69 dependi ...

What is the term for specifying a variable's data type using a set of values instead of a traditional type?

Recently, I stumbled upon some code that introduces a class with specific variables defined in an unconventional manner. export class Foo { id: string = "A regular string" bar: '>' | '<' | '=' | '<=' | ...

Guide on setting up JSME, a chemistry portal integrated with JavaScript, within vuejs

I am looking to integrate the JSME chemistry portal into my Vuejs application. Upon the initial page load, an error is displayed: JSME initialization error: HTML id jsme_container not found. Strangely, upon refreshing the page, the error disappears. How ...

The Vue.js router is malfunctioning

After searching through several posts on Stackoverflow about issues with routes not functioning properly, I have yet to find a solution for why my routes are not working. This is how my router looks: import Vue from 'vue' import Router from &ap ...

Tips for implementing a delay in HTTP requests using RxJS 6.3.0

When I try to use delay with the HTTPClient object, it gives me the following error: Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures. TypeScript Concerns: import { delay } from & ...

Retrieving the input value using ref in Vue 3 and TypeScript

It appears to be a straightforward issue, but I haven't been able to find consistent Vue 3 TypeScript documentation on accessing an input field and retrieving its value from within a function. <template> <Field type="text" ...

What is the process for developing an Android App using a VueJs SPA implemented within Laravel?

I have successfully implemented VueJS in Laravel for Frontend Development. I am now curious if the same VueJs frontend code can be utilized to develop an Android App. If so, what are the necessary steps? I am inexperienced with using Native in Laravel Vue ...

Vue is set up to monitor changes in two connected input fields for user input exclusively

Two input fields are available, where the value of one can affect the other. If a value between 1 and 200 is entered in the level field, Vue will look up the corresponding points for that level and populate the points field with them. Conversely, if a us ...

Bypass React Query execution when the parameter is null

I am facing an issue with a react query problem. I have a separate file containing all the queries: const useFetchApTableQuery = (date: string): UseQueryResult => { const axiosClient = axios.create() const fetchApTableQuery = async (): Promise<A ...

What is the best method for eliminating unsuccessful retries in BullMQ tasks?

I am utilizing BullMQ to run background jobs. My main job is defined with a retry strategy, and I want to ensure that if the main job fails and then its retried attempt fails as well, the failed retries are automatically removed. Since I calculate error th ...

How can the `!` operator be utilized in MikroORM Typescript entities?

How can I declare a key in a JS object with an ! before the colon? MikroORM syntax for class @Entity() export class Post { // Using @PrimaryKey() decorator to designate primary key @PrimaryKey() id!: number; @Property({ type: "date", de ...