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

Pinia Getter中TS错误:Expression Not Callable的原因与解决

问题分析与解决方案

问题根源

你的TypeScript错误出在**TodoState的类型定义**上:

export interface TodoState {
    items: Todo[] | undefined[];
}

这里的Todo[] | undefined[]表示items要么是全部由Todo对象组成的数组,要么是全部由undefined组成的数组。这种数组级别的联合类型会导致TypeScript无法确定items.find的调用签名——两个数组类型的find方法回调参数类型不兼容,因此报错提示该表达式不可调用。

正确处理方式

方案1:修正为元素级联合类型(允许数组含undefined项)

如果业务场景中items数组确实可能存在undefined元素,需将类型改为元素层面的联合,而非数组层面:

export interface TodoState {
    items: (Todo | undefined)[];
}

同时在find回调中处理item为undefined的情况,避免属性访问报错:

const getters = {
    getById: (state: TodoState) => (id: string) => {
        return state.items.find(item => item?.id === id);
    } 
}

方案2:直接定义为Todo数组(更符合常规业务逻辑)

通常Todo列表中的项都是有效的Todo对象,不会存在undefined,因此更合理的类型定义是:

export interface TodoState {
    items: Todo[];
}

此时items.find的类型完全明确,回调中item必然是Todo类型,无需额外修改其他代码。

修正后的完整代码(方案2)

import { defineStore } from "pinia";

export interface Todo {
    id: string;
    title: string;
    done: boolean;
    createdAt: Date;
    updatedAt: Date;
}

export interface TodoState {
    items: Todo[];
}

const state = (): TodoState => ({
    items: [],
});

const getters = {
    getById: (state: TodoState) => (id: string) => {
        return state.items.find(item => item.id === id);
    } 
}

const actions = {}

export const useTodoStore = defineStore('todoStore',{
    state,
    getters,
    actions
})

内容的提问来源于stack exchange,提问作者Tomas Gil Amoedo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:01:21