Subscribe on changes!

Type inference for ref() of an array of objects with refs in them doesn't properly report that the inner refs won't be unwrapped

avatar
Jan 25th 2022

Version

3.2.29

Reproduction link

sfc.vuejs.org/

Steps to reproduce

import { ref } from 'vue';

const store = {
    test: ref('test'),
};

type Store = typeof store;

const initialValues = [store];

const list = ref(initialValues);
list.value[0].test;

const list2 = ref(initialValues) as unknown as Ref<Store[]>;
list2.value[0].test;

console.log('ref or string?', list.value[0].test);

What is expected?

Type inference for the ref function on arrays should know that it doesn't unwrap refs within objects.

What is actually happening?

When hovering over test in the first list.value[0].test line, the type is specified in typescript as (property) test: string.

If you hover over the test field in list2.value[0].test it will show as (property) test: Ref<string>. This is expected since I'm forcing the typing to a Ref<Store[]>, bypassing inference.

The console.log line will show that the proper typing is a string and not a ref.


I'm not sure if this is possible to fix with the type inference or not, but as a newcomer to the reactivity system, it confused me pretty good.

avatar
Jan 25th 2022

This is because, in a reactive array, the value of the object will be set to reactive.

const store = {
    test: ref('test'),
};

type Store = typeof store;

const initialValues = [store];

console.log('store: ',isReactive(store))     //false

const list = ref(initialValues);
console.log('ref([store]): ',isReactive(list.value[0]))  //true  

it automatically unwraps