2
interface Intf {
    prop: ComputedRef<string>;
}

const obj = {} as Intf;

console.log(obj.prop.value);

I have the above code which looks good as what I expected. I can access obj.prop.value and no error was thrown from typescript. However, when I put this ComputedRef<string> inside another reactive object, I cannot retrieve it back as typescript said the prop is in type string instead of ComputedRef<string>. Let see the following codes:

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`!!
mannok
  • 1,712
  • 1
  • 20
  • 30

1 Answers1

3

computed are refs and as all refs, they are automatically unwraped when used inside object created with reactive()

That's the reason why TS tells you re.obj.prop is of type string - you don't need to use .value to access the value, just use re.obj.prop

Michal Levý
  • 33,064
  • 4
  • 68
  • 86
  • let say I have a `reactive({ compute: undefined as ComputedRef | undefined })`. How can I assign a `computed(() => 'value')` in it? I encountered this problem and typescript doesn't allow me to assign the `computed` into `compute` as when the code leaves `reactive` declaration, the `compute` prop is no longer a `ComputedRef`, it becomes a `string` instead! – mannok Nov 04 '20 at 08:31
  • well, I see...interesting problem but different from your original question. Maybe you should create new question and somebody will be able to help. I am not.. – Michal Levý Nov 04 '20 at 13:09