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

Vue3+TS中如何解决空数组ref的never类型问题?

Vue3+TS迁移Todo组件的类型错误解决

错误原因及修复方案

  • Argument of type '{ id: number; title: string; completed: boolean; }' is not assignable to parameter of type 'never':ref([])会被TS默认推断为never[]类型,因为它无法识别数组内元素的结构,必须显式指定数组元素的类型。
  • Property 'completed' does not exist on type 'never':根源和第一个错误一致,由于todos.value的元素被推断为never,访问completed属性自然会报错,指定数组类型后该问题自动解决。
  • Parameter 'index' implicitly has an 'any' type:TS强制要求函数参数必须显式声明类型,这里index作为数组索引,类型应为number。

修改后的完整代码

<script lang="ts">
import { computed, ref } from "vue";
import { defineComponent } from 'vue'

// 定义Todo数据结构的类型
interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

export default defineComponent ({
  setup() {
    const todo = ref("");
    // 显式指定todos为Todo类型的数组
    const todos = ref<Todo[]>([]);
    let id = 0;

    const numberOfCompletedTodos = computed(
      () => todos.value.filter((todoItem) => todoItem.completed).length
    );

    function addTodo() {
      if (!todo.value.trim()) return; // 新增空值判断,避免添加无效待办
      todos.value.push({
        id: id,
        title: todo.value.trim(),
        completed: false,
      });
      todo.value = "";
      id++;
    }

    // 给index参数指定number类型
    function removeTodo(index: number) {
      todos.value.splice(index, 1);
    }

    // 返回模板需要访问的变量和方法
    return {
      todo,
      todos,
      numberOfCompletedTodos,
      addTodo,
      removeTodo
    }
  }
})
</script>

额外提示

  • 新增的空值判断可以过滤用户输入的空白内容,避免生成无意义的待办项。
  • setup函数必须返回模板中要用到的变量和方法,否则模板无法访问这些内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:07:13