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

Nuxt+TypeScript场景下Vue.extend无法识别注入数据类型的问题

解决方案

Vue 2 的 Vue.extend 本身不支持自动推导数组写法的 inject 类型,因为字符串数组没有携带类型信息,TS 无法识别注入属性的类型,所以才会抛出属性不存在的报错。有两种常用的无any解决方案:


方案1:显式给Vue.extend传入泛型参数

Vue.extend 支持传入5个泛型参数,第五位就是自定义扩展的实例属性类型,你可以把所有inject属性的类型定义后传入即可:

import Vue from 'vue';

// 定义所有注入属性的类型
type InjectedProps = {
  b: string // 替换为b属性的实际类型
}

type Data = {
 a: number
}

// 泛型参数依次为:Data类型、Methods类型、Computed类型、Props类型、扩展实例属性类型
export default Vue.extend<Data, Record<string, any>, Record<string, any>, Record<string, any>, InjectedProps>({
 inject: ['b'],
 data():Data{
  const a = 3;
  const c = this.b // 无报错,自动识别为string类型
  return {
   a
  }
 },
 methods:{
  my_method(){
    this.a // 正常识别
    this.b // 正常识别
  }
 }
})

如果你觉得泛型参数太长,也可以单独在使用的地方做窄类型断言,比as any更安全:

const c = (this as Vue & {b: string}).b

方案2:使用装饰器写法(项目支持的前提下)

如果你的Nuxt项目已经开启了装饰器支持,用vue-property-decorator的@Inject装饰器可以更方便的实现类型推导:

import { Component, Vue, Inject } from 'vue-property-decorator'

@Component
export default class MyComponent extends Vue {
  // 直接声明注入属性和对应类型
  @Inject() readonly b!: string
  a: number = 3

  my_method() {
    this.a // 类型正常
    this.b // 类型正常
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:42:00