【问题标题】:Typescript how to add new item to empty array of objects打字稿如何将新项目添加到空的对象数组中
【发布时间】:2018-06-10 06:44:28
【问题描述】:

我在 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 添加新项目,但出现错误:Argument type {..} is not assignable to parameter of type never 如何向数组中添加新项目?

【问题讨论】:

  • response.data 是一个数组吗?
  • 是的,response.data 是对象数组:{ id : '-1', userid : '1', name : 'newtab' }
  • 问题是数组 userfilterresults 一开始是空的

标签: javascript arrays typescript vuejs2 vue-component


【解决方案1】:

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

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

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

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

我不熟悉 Vue 的类型,但这是根本原因。

试试

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

看看有没有帮助。

【讨论】:

    【解决方案2】:

    userfilterresults:any= [] ;

    addtab() {

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

    } }

      this.userfilterresults.push(obj);
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2019-05-27
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 2020-01-01
      • 2021-10-27
      相关资源
      最近更新 更多