Typescript how to add new item to empty array of objects

11,004

You need to declare a type for userfilterresults.

By default, for let x = [], type of x will be never[].

You need to specify it explicitly or mark it as any[]. e.g.

let x: any[] = []
let y: CustomType[] = []

I'm not familiar with the typings of Vue, but that is the underlying reason.

Try

data: {
  userfilterresults: [] as any[]
}

and see if that helps.

Share:
11,004

Related videos on Youtube

Robert
Author by

Robert

Updated on June 04, 2022

Comments

  • Robert
    Robert almost 2 years

    I have component in vue 2 which is written in typescript:

     data: {
        userfilterresults: []
      },
      mounted() {
        axios.get("/Tasks/GetTasks")
          .then(response => {
            this.userfilterresults = response.data;
          });
      },
      methods: {
        addtab() {
          // this push bellow is the reason of the error:
          this.userfilterresults.push({
            id : '-1',
            userid : '1',
            name : 'newtab'
          });
    

    And I want to add new item to existed array userfilterresults but I've got error: Argument type {..} is not assignable to parameter of type never How I can add new item to the array?

    • Jonathan Dion
      Jonathan Dion over 6 years
      response.data is an array?
    • Robert
      Robert over 6 years
      yes, response.data is the array of objects: { id : '-1', userid : '1', name : 'newtab' }
    • Robert
      Robert over 6 years
      the problem is that at the begin the array userfilterresults is empty