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

Rob*_*ert 2 javascript arrays typescript vue-component vuejs2

我在 vue 2 中有一个用打字稿编写的组件:

 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'
      });
Run Code Online (Sandbox Code Playgroud)

我想向现有数组 userfilterresults 添加新项目,但出现错误:参数类型 {..} 不可分配给 never 类型的参数 如何向数组添加新项目?

uni*_*nal 7

您需要声明一个类型userfilterresults

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

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

let x: any[] = []
let y: CustomType[] = []
Run Code Online (Sandbox Code Playgroud)

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

尝试

data: {
  userfilterresults: [] as any[]
}
Run Code Online (Sandbox Code Playgroud)

看看是否有帮助。