【问题标题】:vue 3 & typescript - Cannot access ComputedRef<> when it is located inside a reactive();vue 3 & typescript - 当 ComputedRef<> 位于 reactive() 内时无法访问它;
【发布时间】:2020-11-04 07:34:46
【问题描述】:
interface Intf {
    prop: ComputedRef<string>;
}

const obj = {} as Intf;

console.log(obj.prop.value);

我有上面的代码,看起来和我预期的一样好。我可以访问obj.prop.value,并且打字稿没有抛出任何错误。但是,当我将这个ComputedRef&lt;string&gt; 放在另一个反应对象中时,我无法将其取回,因为打字稿说prop 的类型是string 而不是ComputedRef&lt;string&gt;。让我们看看以下代码:

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`!!

【问题讨论】:

    标签: typescript reactive-programming typescript-typings reactive vuejs3


    【解决方案1】:

    computed 是 refs,并且作为所有 refs,当在使用 reactive() 创建的对象内部使用时,它们会自动成为 unwraped

    这就是为什么 TS 告诉你 re.obj.prop 是字符串类型的原因 - 你不需要使用 .value 来访问该值,只需使用 re.obj.prop

    【讨论】:

    • 假设我有一个reactive({ compute: undefined as ComputedRef&lt;string&gt; | undefined })。如何在其中分配computed(() =&gt; 'value')?我遇到了这个问题,打字稿不允许我将computed 分配给compute,因为当代码离开reactive 声明时,compute 道具不再是ComputedRef&lt;string&gt;,它变成了string而是!
    • 好吧,我明白了...有趣的问题,但与您原来的问题不同。也许您应该创建新问题,并且有人可以提供帮助。我不是..
    猜你喜欢
    • 2022-01-09
    • 2021-07-08
    • 2021-03-12
    • 2021-10-19
    • 2018-07-28
    • 2021-07-05
    • 2019-07-01
    • 1970-01-01
    相关资源
    最近更新 更多