Typescript如何将新项添加到空对象数组中

问题描述 投票:1回答:2

我在vue 2中有一个用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'
      });

我想添加新项目到现有数组userfilterresults但我有错误:参数类型{..}不能分配给类型参数如何我可以添加新项目到数组?

javascript arrays typescript vuejs2 vue-component
2个回答
1
投票

你需要为userfilterresults声明一个类型。

默认情况下,对于let x = []x的类型将是never[]

您需要明确指定它或将其标记为any[]。例如

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

我不熟悉Vue的类型,但这是潜在的原因。

尝试

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

看看是否有帮助。


0
投票

userfilterresults:any = [];

addtab(){

  var obj={
     id : '-1',
    userid : '1',
    name : 'newtab'

} }

  this.userfilterresults.push(obj);
© www.soinside.com 2019 - 2024. All rights reserved.