Vue中定义Todo[]类型计算数组遇重载匹配错误问题
问题:Vue3 + TypeScript 创建Todo[]类型计算属性报错
我想要创建一个Todo[]类型的计算属性数组,但遇到了如下错误:
No overload matches this call.
Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<Todo[]>', gave the following error.
Overload 2 of 2, '(options: WritableComputedOptions<Todo[]>, debugOptions?: DebuggerOptions | undefined): WritableComputedRef<Todo[]>', gave the following error.
相关代码
todo.ts
export class Todo { checked: boolean; text: string constructor(checked: boolean, text: string) { this.checked = checked; this.text = text } }
Todos.vue
<script setup lang="ts"> import { computed } from '@vue/reactivity'; import { ref } from 'vue' import { Todo } from '../todo' let todos = ref<Todo[]>([]); const filter = ref<string>('all') const filteredTodos = computed<Todo[]>(() => { if(filter.value == "all") return todos; if(filter.value == "active") return todos.value.filter((item) => !item.checked) if(filter.value == "completed") return todos.value.filter((item) => item.checked) }) </script>
解决方案
错误根源在于filter.value为"all"的分支:你返回的是ref对象todos,而非它的实际值todos.value。计算属性的 getter 要求返回Todo[]类型,但todos本身是Ref<Todo[]>类型,类型不匹配导致了重载匹配失败的报错。
只需要把该分支的返回值改成todos.value,所有分支就都返回Todo[]类型,类型校验就能通过:
修改后的Todos.vue
<script setup lang="ts"> import { computed } from '@vue/reactivity'; import { ref } from 'vue' import { Todo } from '../todo' let todos = ref<Todo[]>([]); const filter = ref<string>('all') const filteredTodos = computed<Todo[]>(() => { if(filter.value == "all") return todos.value; // 这里改成todos.value if(filter.value == "active") return todos.value.filter((item) => !item.checked) if(filter.value == "completed") return todos.value.filter((item) => item.checked) }) </script>
内容的提问来源于stack exchange,提问作者SkylineFX
相关产品推荐
相关产品推荐

