You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+TypeScript+ESLint下如何正确定义对象数组?

Vue3 + TypeScript 解决数组类型推断为never的问题

问题原因

当你在data中将blah2初始化为空数组[]时,TypeScript无法推断出数组元素的具体类型,会默认把它判定为never[]类型,因此调用push方法添加元素时会触发类型不匹配的错误。

正确定义方式

方式1:在data中使用类型断言

直接对空数组做类型断言,指定数组元素的结构:

data() {
  return {
    blah: '',
    blah2: [] as { s: string; b: boolean }[]
  }
}

方式2:提前定义接口(更易维护)

先声明元素的接口类型,再用断言指定数组类型,适合复杂结构或多处复用的场景:

// 先定义元素接口
interface Entry {
  s: string;
  b: boolean; // 注意用小写的boolean基本类型,不要用Boolean构造函数
}

export default {
  data() {
    return {
      blah: '',
      blah2: [] as Entry[]
    }
  },
  methods: {
    addEntry(): void {
      this.blah2.push({ s: 'whatever', b: false });
    }
  }
}

方式3:Composition API写法(Vue3推荐)

如果使用Composition API,可以直接通过ref声明数组类型:

import { ref } from 'vue';

interface Entry {
  s: string;
  b: boolean;
}

export default {
  setup() {
    const blah = ref('');
    // 直接指定ref的泛型类型
    const blah2 = ref<Entry[]>([]);

    const addEntry = () => {
      blah2.value.push({ s: 'whatever', b: false });
    };

    return { blah, blah2, addEntry };
  }
}

为什么你之前的写法无效

  • blah2: any[] = []:Vue选项式API的data是返回对象的函数,不能直接在对象属性上声明类型,需用类型断言。
  • Array<{ s: string, b: Boolean }> = Array():选项式data中不能直接赋值类型,且Boolean是构造函数,应使用boolean基本类型。
  • Array<{ s: string, b: Boolean }>[] = []:这定义的是数组的数组,和你需要的单层级数组类型不匹配。
  • { s: string, b: Boolean } = []:试图把数组赋值给单个对象类型,类型完全不匹配。
  • { s: string, b: Boolean }[] = []:选项式data中不能直接这样声明类型,需要配合类型断言使用。
  • any[{ s: string, b: Boolean }] = []:语法错误,any的使用方式不正确。

内容的提问来源于stack exchange,提问作者Graham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:40:20