typescriptvue.jsvuejs3vue-typescript

Vue's ref doesn't maintain types of nested private properties


This problem occurs both with arrays and objects. Using shallowRef instead of ref solves it but I often need deep reactivity. Now I use casting, but I'm not happy with it. What's the best way to address this problem?

class Bar {
    private val = 1;
}

class Foo {
    private bar = new Bar();
}

const fooRef = ref(new Foo());

const foo: Foo = fooRef.value; // Property bar is missing in type {} but required in type Foo
const bar = fooRef.value.bar; // Property bar does not exist on type {}

const baz = ref([new Foo()]); 
const z = baz.value[0].bar.val; // Property bar does not exist on type {}

Packages I use:

"typescript": "^5.6.3",
"vue": "^3.5.12",

Solution

  • ref creates deeply reactive object that does ref unwrapping, and ref type works by extracting public members, this is a way for it to implement unwrapping. This is important for class types because their compatibility requires their private members to match.

    So it's expected that fooRef.value type may not be Foo, at least when the class implementation uses reactivity API. This requires to use type assertion when a developer is certain that the type is correct.

    This can be done at the time where a value is consumed:

    const foo = fooRef.value as Foo;
    

    Or when a ref is created:

    const fooRef = ref(new Foo()) as Ref<Foo>;
    

    Which is not the same as ref<Foo>(new Foo()), the latter works the same way as ref(new Foo()).