vue 3 & typescript - 当 ComputedRef<> 位于 reactive() 内部时无法访问
interface Intf {
prop: ComputedRef<string>;
}
const obj = {} as Intf;
console.log(obj.prop.value);
我有上面的代码,看起来和我预期的一样。我可以访问 obj.prop.value,并且 TypeScript 没有抛出错误。然而,当我把这个 ComputedRef<string> 放入另一个响应式对象中时,我无法取回它,因为 TypeScript 说 prop 的类型是 string 而不是 ComputedRef<string>。我们来看下面的代码:
interface Intf {
prop: ComputedRef<string>;
}
const re = reactive({
obj: {} as Intf
});
console.log(re.obj.prop.value); // typescript shown error on this line, `re.obj.prop` is with type `string` instead of `ComputedRef<string>`. At the moment, I cannot retrieve `prop.value` by accessing `prop` as well, since prop is a `ComputedRef<string>` and I should get its value by accessing `prop.value`!!
答案#1
computed 是 refs,和所有 refs 一样,当在使用 reactive() 创建的对象内使用时,它们会被自动解包
这就是为什么 TS 告诉你 re.obj.prop 的类型是字符串——你不需要使用 .value 来访问值,只需使用 re.obj.prop