How to define an array of objects in data using Vue.js and TypeScript

Encountering errors when attempting to declare an array of objects in Vue.js 3 + TypeScript. The code snippet includes a template, script, and style sections.

<template>
  <ul >
    <li v-if="!items.length">...loading</li>
    <li v-for="item in items" :key="item.id">
        <slot name="item" v-bind="item"></slot>

    </li>
  </ul>
</template>

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

export default defineComponent({
    name: 'child-slot-component',
    data() {
    return {
        items: []
    }
  },
    mounted() {
        setTimeout(() => {
      this.items = [
        { id: 1, body: 'Scoped Slots Guide', username: 'Evan You', likes: 20 },
        { id: 2, body: 'Vue Tutorial', username: 'Natalia Tepluhina', likes: 10 }
      ]
    }, 1000)
    },
})
</script>

<style scoped>
    ul{
        list-style-type: none;
    }

</style>

Encountering error Type 'number' or 'string' is not assignable to type 'never'.ts(2322) because the property was declared as never when initializing the items array. Desiring to declare objects with specific properties such as {id:number, body:string,username:string, likes:number}[]

Inquiring about the correct way to handle this declaration using TypeScript.

Any insights on configuration adjustments that may be required would be appreciated. Thank you!

This is the content of my tsconfig.json file:

{
  "compilerOptions": {
    "target": "esnext",
    ...
}

Similarly, here are excerpts from my vue.config.js, babel.config, shims-vue.d.ts, and .eslintrc.js files.

The configurations provided above follow the standard setup generated by 'vue create app-name' command.

Answer №1

To resolve the TypeScript error, it is recommended to explicitly define the structure of your items array beforehand. You can achieve this by specifying the type of elements in the array as shown below:

items: [] as { id: number, content: string, author: string, rating: number }[]

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

Issue with displaying errors in vee-validate when using Vue.js Axios (More details provided)

When working on my Vue project, I encountered an issue while using Vee-Validate and Axios. During an API call to register a user, if the email is already in use, an error is thrown. To handle this error and display the error message, I used the following ...

What is causing Angular to consistently display the first object in the array on the child view, while the child .ts file correctly prints information from a different object?

Once a card of any object is clicked, the information of that specific object will be printed to the console. However, the child view will only display the details of the first object in the array it retrieves from. All pages are included below. A visual e ...

Tips for implementing API proxying in a production environment with Vue 2

I have been exploring the vuejs-templates documentation and came across section3, which discusses how to proxy API requests in development mode. I am wondering how to achieve a similar setup for production. Specifically, when running the production version ...

Utilizing the map function to incorporate numerous elements into the state

I'm struggling with 2 buttons, Single Component and Multiple Component. Upon clicking Multiple Component, my expectation is for it to add 3 components, but instead, it only adds 1. import React, { useState, useEffect } from "react"; import ...

Efficient method for iterating through three arrays that have matching values and satisfy specified conditions in TypeScript

Struggling to speed up my Excel sheet creation time, currently taking over 20 seconds. I'm using the code below to compare three arrays and get the desired output: for (let i = 0; i < this.arrayNumberOne[0].length; i++) { let orangeOne = this.a ...

The process of downloading an image from Spring Boot using VueJs and displaying it within an <img> tag

I have created a Spring Boot backend with a Vue frontend. I am having issues when trying to download and display an image from Google Cloud Storage in my application. Sometimes the downloaded image appears to be cut off, as if not all bytes were sent. Howe ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...

What is the best method for calculating the total sum by multiplying the values in an array?

In my current project, I have an array consisting of multiple objects, each containing a property named "amount". My goal is to sum up all these amount values to get the total. Initially, I attempted to use a for loop but encountered an issue where settin ...

Passing parent props to child components in Vue.js - A comprehensive guide!

Trying to understand the process of passing a prop from parent to child components. If I include the prop attribute with the #id within the child component tag, like Image cid="488484-49544894-584854", it functions correctly. However, I am interested in u ...

What is the best way to test chained function calls using sinon?

Here is the code I am currently testing: obj.getTimeSent().getTime(); In this snippet, obj.getTimeSent() returns a Date object, followed by calling the getTime() method on that Date. My attempt to stub this functionality looked like this: const timeStu ...

The directive does not function properly when used across multiple files

Struggling with @Directives and @Hostlisteners - seeking assistance The directive added to the input seems unresponsive, failing to trigger any events or console.log(). I'm puzzled and frustrated as there appears to be a missing piece of the puzzle t ...

Troubleshooting Angular 14 Custom Form Control Display Issue

I'm facing an issue while attempting to develop a custom form control in Angular 14. Despite no errors showing up in the console, my custom control is not rendering as expected. When inspecting the Elements tab in the console, I can see the parent com ...

vue-spa breadcrumbs component

I am currently working on enhancing the navigation of my vue-spa project by implementing breadcrumbs. These breadcrumbs should be capable of displaying properties as breadcrumb-items, and each part of a route must be correctly identified as a breadcrumb-it ...

Create a named scopedSlot dynamically

Looking to incorporate the following template into my component's render function, but struggling with how to do so. This is the current template structure: <template> <div> <slot name="item" v-for="item in filte ...

Hidden content from Vue router view

My goal is to have the navigation pane overlaying the content of the page, but instead, it is being appended to the bottom where the end of the navigation drawer would be. I've experimented with different variations to display data using navigation dr ...

What is the reason behind create-next-app generating .tsx files instead of .js files?

Whenever I include with-tailwindcss at the end of the command line, it appears to cause an issue. Is there any solution for this? npx create-next-app -e with-tailwindcss project_name ...

Sending Information to Routes - Error: No Routes Found to Match

I recently tried implementing a solution from an article () to pass an ID between modules in order to use it as a search filter. However, I encountered the "cannot match any routes" error and have been struggling for some time since I'm new to Angular ...

Tips for choosing an HTML element using Playwright with TypeScript

My goal is to use playwright with typescript in order to select a specific html element. The element I am trying to target has the class "ivu-select-dropdown" and a specific style. <div class="ivu-select-dropdown" style="position: absolut ...

Create a prototype class in NuxtJS Vue

What is the correct way to set a class to prototype in Vue NuxtJS? I have created a plugin Here is my nuxt.config.js file: plugins: [ { src: "~/plugins/global.js" }, ], The global.js file contains: import Vue from "vue"; import CustomStore from "dev ...

Building a Model Class with redux-orm and TypeScriptCreating a new Model Class with

I've been successfully using redux-orm with JavaScript, however, I'm facing issues when trying to convert my code to TypeScript. Even though I have already implemented the render() method in my Folder Model Class, the TypeScript transpiler is sh ...