Using TypeScript to specify data types in the Vue data object

I am currently utilizing Vue.js with Typescript in a webpack project.

Following the guidelines provided in the Recommended Configuration in my tsconfig.json, I have set:

"strict": true,

Within one of my components, I have:

declare interface Player {
    cod: string,
    param: string
  }

export default Vue.extend({
    name: 'basecomponent',
    data() {
      return {
        players: []
      };
    },
    created() 
      let self = this
      axios.get('fetch-data')
        .then((response) => {
          let res: Players[] = response.data;
          for(let i = 0; i < res.length; i++){
              self.players.push(res[i]);
          }
        })
        .catch((error: string) => {
          console.log(error);
       });
    },
 });

However, when attempting to compile, I encounter the following error:

 error TS2345: Argument of type 'Player' is not assignable to parameter of type 'never'.

I suspect that players: [] has the type never[].

My inquiry is: How can I determine the types for Vue data object properties?

Answer №1

Expanding on the response from Joshua, it is advisable to specify the type of players within the code directly to prevent it from becoming overly verbose as your dataset grows in size.

data() {
  return {
    members: [] as Member[]
  };
},

Alternatively:

data() {
  return {
    participants: new Array<Player>()
  };
},

Answer №2

Here is an example that should function as intended:

interface User {
  id: number,
  name: string
}

interface UserData {
  users: User[]
}

export default Vue.extend({
  name: 'usercomponent',
  data(): UserData {
    return {
      users: []
    };
  },
})

Answer №3

Make sure to declare a return value in your data method.

This will help TypeScript understand the expected type for the players property.

Simply update the data() { line with the following:

data() : {
  players: Array<any>, // Consider using a more specific type instead of `any`
} {
  return {
    players: []
  };
},

By making this change, the players property will be correctly typed as an Array of any.

Answer №4

Discovering an alternative approach that closely resembles the traditional syntax, yet maintains concise code.

data() {
  return new function {
    members: Member[] = []
   }();
},

Answer №5

The use of the '<>' syntax for type assertion is prohibited. Instead, please utilize the 'as' syntax as shown below:

Here is a visual representation:

teams: [] as Team[]

Answer №6

If anyone happens upon this in the future, here is the solution that resolved my issue. It may be a bit more verbose, but it ensures proper type inference throughout the Vue.extend() component definition:

interface Player {
  cod: string,
  param: string
}

// Include any properties defined in the `data()` return object here.
interface Data {
  players: Player[];
}

// Include any methods defined in "methods()" here.
interface Methods {}

// Include any computed properties from "computed()" here.
interface Computed {}

// Declare any component props here.
interface Props {}

export default Vue.extend<Data, Methods, Computed, Props>({
    name: 'basecomponent',
    data() {
      return {
        players: []
      };
    },
    // It's recommended to switch to the "mounted()" component lifecycle, as issues can occur when modifying data within "created()".
    created() {
      // The following lines are optional.
      // let self = this
      // By typing the Axios.get() method like this, the .data property is automatically typed.
      axios.get<Players[]>('fetch-data')
        .then(({ data }) => {
          // The next lines are optional.
          // let res: Players[] = response.data;
          // for(let i = 0; i < data.length; i++){
          //     self.players.push(data[i]);
          // }
          this.players = data;
        })
        .catch((error: string) => {
          console.log(error);
       });
    },
 });

Answer №7

In order to avoid detailing the entire data structure, it may be more practical to start by explicitly defining players as a variable with a specified type:

export default Vue.extend({
    name: 'basecomponent',
    data() {
      const players: Player[] = [];
      return {
        players: players
      };
    },
...

This approach should also apply to other intricate types, not limited to arrays. However, I am still figuring out how to prevent volar from restricting the union type based on the initializer value -_-

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

Updating the page dynamically in React/Redux by making API calls based on user submissions

My current task involves calling an API with Redux, triggering the call based on a form submission. If the query is empty, it should return all lists; otherwise, it should only return lists that match the query. // List.tsx import React, { useEffect, useS ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Tips on linking a changing object using v-bind in Vue

Can someone help me with a query regarding the v-bind dynamic object? When dealing with binding in a completely dynamic object, how can I bind properties using operation expressions? How can I ensure that the attributes stay observable and update automatic ...

Error Encountered When Trying to Import Mocha for Typescript Unit Testing

Here's a snippet of code for testing a Typescript project using mocha chai. The test case is currently empty. import {KafkaConsumer} from '../infrastructure/delivery/kafka/kafka-consumer'; import {expect} from 'chai'; import {descr ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

What is the best way to write a function in typescript that verifies whether the argument extends a type argument and then returns the argument?

I need to create a function that checks if the argument's type extends a specific type variable and then returns the argument. Something like this: declare function checkType<T, X extends T>(argument: X): X However, TypeScript gives an error wh ...

Clicking on a button will trigger the opening of a modal dialog

I encountered an issue with the following code: <sepa-modal ref="sepaModal" /> <b-card id="show-btn" class="card-modal" @click="openSepaModal()" > </b-card> openSepaModal ...

What is the best way to utilize the next-env.d.ts file within Next.js?

In my Next.js TypeScript project, I came across a file named next-env.d.ts. This got me thinking about how I can declare enums that would be accessible across all my Next.js files. Can you guide me on how to achieve this and use the enums throughout my p ...

Tips on modifying the selected type key name through Pick?

I currently have this structure: type Product = { name: string } and I am looking to extract the name property and use it in a different type declaration like so: type NewProduct = Pick<Product, 'name'> Now, I want to rename name as new ...

Tips on creating type definitions for CSS modules in Parcel?

As someone who is brand new to Parcel, I have a question that may seem naive. In my project, I am using typescript, react, less, and parcel. I am encountering an error with typescript stating 'Cannot find module 'xxx' or its corresponding t ...

A guide on passing variables to the MUI styled function within ReactJS

Is it possible to pass a variable directly to the styled function in order to conditionally change style properties while using MUI styled function? I want to achieve something like this: borderColor: darkMode ? 'white' : 'black' const ...

Using Vue.js to dynamically populate all dropdown menus with a v-for loop

Getting started with vue.js, I have a task where I need to loop through user data and display it in bootstrap cols. The number of cols grows based on the number of registered users. Each col contains user data along with a select element. These select ele ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

Issue with ngx-bootstrap custom typeahead feature malfunctioning

I'm facing an issue while trying to develop a customized typeahead feature that is supposed to search my API every time the user inputs something, but it's not functioning as expected. The autocomplete() function isn't even getting accessed. ...

What is the method for customizing the background color in a .vue file using Bootstrap?

Can anyone assist me in updating the background color of a div class from grey to white? The code is within a .vue file using Bootstrap and includes an enclosed SVG file. Here's the snippet: <div class="text-left my-3 bg-white"> <button var ...

Angular 2: Capturing scroll events from the parent element within a Directive

One of the challenges I encountered is with a directive called [appInvalidField] that functions like a custom tooltip for validation purposes. To ensure it appears above everything else within dialogs, I attach it to the body and position it near the relev ...

What steps should I take to address this issue using IONIC and TypeScript?

Running into an issue with my TypeScript code for an Ionic project. I'm attempting to pass the value of the variable (this.currentroom) from the getCurrentRoom() function to another function (getUser()) but it's not working. Here's my chat s ...

Customizing the text color of steps in a v-stepper component using Vuetify.js

When working with the v-stepper component of VuetifyJS, it is easy to change the color of the steps themselves by using the `color` prop. But how can I alter the text of each step? Specifically, I am looking to modify the color of the text that says Name ...