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

Vue3插件注入函数报错:Cannot invoke an object which is possibly 'undefined'

Vue3 inject全局函数时TS报错的解决方案

问题描述

我有一个Vue3插件,其中包含一些实际存在且运行正常的全局函数。我在组件中使用inject命令引入它:

const translate = inject<Function>('translate')

现在我本应可以直接调用该函数,比如在computed中:

const parsedCategories = computed(() => {
    const categories = settingsApi.value?.companyCategories ? settingsApi.value.companyCategories : [];

    if( !categories.length ) return []

    let result = [];

    categories.forEach((item: any) => {
        result.push({
            'title': translate(item.translations, 'company_category'),
            'value': item.id
        })
    })

    return result
})

但构建时,这一行:

'title': translate(item.translations, 'company_category'),

出现报错:Cannot invoke an object which is possibly 'undefined'

虽然可通过添加判断解决:

'title': translate ? translate(item.translations, 'company_category') : '',

但我不想每次调用插件函数都写这种判断,请问我哪里操作有误?插件是按官方文档实现的。

解决方案

1. 给inject添加非空断言

TS报错的核心是inject<Function>('translate')的返回类型为Function | undefined,TS无法确定该注入项一定存在。可以通过非空断言!明确告诉TS该值必然存在:

const translate = inject<Function>('translate')!

2. 用InjectionKey优化类型与注入逻辑

如果插件是全局注册且translate必然存在,建议通过InjectionKey定义强类型,让TS自动识别注入项非空:

  1. 新建类型声明文件(如types/vue.d.ts):
import type { InjectionKey } from 'vue'

// 定义符合函数实际参数的类型
export const translateKey: InjectionKey<(translations: any, key: string) => string> = Symbol('translate')
  1. 在插件注册时使用该Key提供函数:
import { translateKey } from './types/vue'

export default {
  install(app) {
    const translate = (translations: any, key: string) => {
      // 你的函数实现逻辑
    }
    app.provide(translateKey, translate)
  }
}
  1. 组件中通过Key注入:
import { translateKey } from '@/types/vue'

const translate = inject(translateKey)
// 此时translate类型为确定的函数,不会触发undefined报错

3. 设置inject默认值

如果允许极端场景下有兜底实现,可以给inject设置默认空函数:

const translate = inject<Function>('translate', () => '')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:16:08