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

Vue+TypeScript类型错误:Ref<…>无法赋值给Ref<UseDraggable>

解决Vue+TypeScript中Ref的类型不匹配问题

错误原因

当用ref()包裹包含ref/computed的对象时,Vue会自动递归解包内部的响应式值,导致TypeScript推断出的对象属性类型是原始值(如number),而非UseDraggable接口要求的Ref<number>/ComputedRef<...>,因此出现类型不兼容错误。

解决方案

方案1:使用shallowRef(推荐)

shallowRef不会递归解包内部响应式对象,能完整保留UseDraggable接口要求的类型结构:

import { shallowRef, ref, computed } from 'vue'

// 用shallowRef替代ref,保留内部响应式属性的类型
const defaultUseDraggable: Ref<UseDraggable> = shallowRef({
  x: ref(0),
  y: ref(0),
  isDragging: computed(() => false),
  style: computed(() => 'left:0px;top:0px;'),
  startDrag: () => {}
})

draggables.value.set(id, defaultUseDraggable)

方案2:类型断言

如果必须使用ref,可以通过类型断言明确指定类型,绕过TypeScript的自动推断:

import { ref, computed } from 'vue'

const defaultUseDraggable = ref({
  x: ref(0),
  y: ref(0),
  isDragging: computed(() => false),
  style: computed(() => 'left:0px;top:0px;'),
  startDrag: () => {}
}) as Ref<UseDraggable>

draggables.value.set(id, defaultUseDraggable)

补充说明

之前尝试用computed虽然能存入Map,但ComputedRef是只读的,无法修改内部属性,不符合你需要同步修改的需求,因此不适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 07:15:06