Search code examples
typescriptvue.jsvuejs2typeerrorvue-composition-api

How to solve Vuejs composition API's Ref() type Error?


I am using vue composition API and using a ref for an array of objects which each object has a value property, it seems that the typescript confusing ref's value with the property value inside of each array:

enter image description here

As you see in the above picture, typescript telling us the type of arr is an array of object which contains name and value, but when i used ref, it detects the wrong type. even if i used as conversion like below the problem wont solve:

const arr2 = ref(arr as { name: string; value: number }[]);

But when i change the value property to value2 or something else, it will work: enter image description here

update:

here is another problem which i have faced today:

enter image description here

I'm wondering how should i solve this type error?


Solution

  • It's a shame that you've used an image to show your code, because I have to retype it all again.

    Yes, it seems clear that using 'value' as a key in your object confuses Typescript. You can get round it by declaring an interface, which you then also use to declare arr2

        interface thing {
            name: string,
            value: number
        };
    
        const arr: thing[] = [
            {name: "x1", value: 1},
            {name: "x2", value: 2}
        ];
    
        const arr2: Ref<thing[]> = ref(arr);
    
        arr2.value.forEach(item => console.log(item.name + ':' + item.value));
    

    However the best way to get round it is not to use 'value' as a key in your objects obviously, because it's likely a reserved word in Javascript and/or Typescript.