Vue+TypeScript中this.$refs报Object is of type 'unknown'解决方法
问题原因
该报错确实是未给this.$refs定义对应类型导致的。
在TypeScript环境下编写Vue类组件时,$refs的默认类型为{ [key: string]: unknown },所有通过this.$refs.xxx获取的DOM节点或组件实例都会被推导为unknown类型。TypeScript不允许直接访问unknown类型上的属性,因此会抛出*Object is of type 'unknown'*的类型错误。这类错误仅在TS类型检查阶段触发,不会侵入运行时逻辑,和你描述的「请求可正常运行」的现象完全吻合。
解决方法
根据项目场景可选择以下两种修复方案:
- 方案1:类内声明
$refs全局类型(推荐)
在组件类中通过非空断言明确标注$refs下每个ref对应的类型,后续在类的任意方法中访问this.$refs时都能获得正确的类型提示与校验。如果ref绑定的是原生DOM元素,直接写对应DOM类型即可;如果绑定的是自定义组件,替换为对应组件的类类型即可,示例代码:import Vue from 'vue'; import axios from 'axios'; export default class FormPage extends Vue { // 声明$refs的完整结构与每个ref的类型 $refs!: { coinbase: { key: string; secret: string }, coinbase_pro: { key: string; secret: string; passphrase: string } } sendTradeRequest() { const object = { coinbase:{ key: this.$refs.coinbase.key, secret: this.$refs.coinbase.secret }, coinbase_pro:{ key: this.$refs.coinbase_pro.key, secret: this.$refs.coinbase_pro.secret, passphrase: this.$refs.coinbase_pro.passphrase } }; axios.post('/get_trade', object).then(response => { console.log(response.data); }) } } - 方案2:访问时做临时类型断言(适合快速修复场景)
如果不需要全局类型校验,也可以在获取ref时通过as关键字做类型断言,手动指定当前ref的类型结构:sendTradeRequest() { // 单独对每个ref做类型断言 const coinbaseRef = this.$refs.coinbase as { key: string; secret: string }; const coinbaseProRef = this.$refs.coinbase_pro as { key: string; secret: string; passphrase: string }; const object = { coinbase:{ key: coinbaseRef.key, secret: coinbaseRef.secret }, coinbase_pro:{ key: coinbaseProRef.key, secret: coinbaseProRef.secret, passphrase: coinbaseProRef.passphrase } }; axios.post('/get_trade', object).then(response => { console.log(response.data); }) }
如果ref绑定的是自定义Vue组件,直接将上述类型替换为对应组件的类即可,TS会自动推导组件实例上对外暴露的所有属性和方法,不需要额外重复定义字段。
内容的提问来源于stack exchange,提问作者DamTan
相关产品推荐
相关产品推荐

