vue 3 & typescript - 当 ComputedRef<> 位于 reactive() 内时无法访问它;
vue 3 & typescript - Cannot access ComputedRef<> when it is located inside a reactive();
interface Intf {
prop: ComputedRef<string>;
}
const obj = {} as Intf;
console.log(obj.prop.value);
我有上面的代码,看起来不错,符合我的预期。我可以访问 obj.prop.value
并且打字稿没有抛出任何错误。但是,当我将此 ComputedRef<string>
放入另一个反应对象时,我无法将其取回,因为打字稿说 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`!!
computed
是 refs 并且与所有 refs 一样,当在使用 reactive()
创建的对象内部使用时,它们自动 unwraped
这就是为什么 TS 告诉你 re.obj.prop
是字符串类型的原因 - 你不需要使用 .value
来访问值,只需使用 re.obj.prop
interface Intf {
prop: ComputedRef<string>;
}
const obj = {} as Intf;
console.log(obj.prop.value);
我有上面的代码,看起来不错,符合我的预期。我可以访问 obj.prop.value
并且打字稿没有抛出任何错误。但是,当我将此 ComputedRef<string>
放入另一个反应对象时,我无法将其取回,因为打字稿说 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`!!
computed
是 refs 并且与所有 refs 一样,当在使用 reactive()
这就是为什么 TS 告诉你 re.obj.prop
是字符串类型的原因 - 你不需要使用 .value
来访问值,只需使用 re.obj.prop