【Vue+TS】添加全局自定义属性后,在组件中通过this调用时找不到类型

前言:

一般在项目中都会封装自己的一些方法,比如把一些工具类方法放在util.ts里,比如:

// src/common/util.ts
function deepClone(obj, map) {}
function debounce(fn, delay) {}

然后在main.js里进行注册

// main.ts
import util from '@/common/util'

export function createApp() {
    ...
	app.config.globalProperties.$util = util
	return {
		app
	}
}

如果你用的是组合式api,那么直接导入即可;可如果是使用的选项式api,在组件内通过this.$util调用时,就会提示类型错误:

类型“CreateComponentPublicInstance<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions>>> & {}, unknown, { rectData: string; isShowPanel: boolean; ... 10 more ...; serverTime: string; }, ... 15 more ..., { ...; } | {}>”上不存在属性“$util”。ts(2339)

在这里插入图片描述
这时需要用到Vue的ComponentCustomProperties 来为Vue实例加上我们自定义的类型提示。

解决方案

在src下创建一个shims-vue.d.ts文件,加入以下代码:

import { ComponentCustomProperties } from 'vue'
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $util: any
  }
}

这时再去原来的位置看,红色波浪线应该已经没了,如果还有,可以尝试重启vscode。

这里我将$util的类型注解为any,这样可以应对任何情况,但不推荐这么做,不然就浪费ts的类型提示了。所以我们可以这样修改:

  1. 在src/下创建types文件夹,并创建一个util.d.ts文件,内容如下:
export type Util = {
  formatRptType(name: string, type?: string): string
}

然后在shims-vue.d.ts 中将代码修改为:

import { ComponentCustomProperties } from 'vue'
import { Util } from '@/types/util'

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $util: Util
  }
}

以后如若还有其它自定义的全局属性,都可以依葫芦画瓢添加提示。

这样,再去对应的调用处就可以看到提示了:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值