Home > Software engineering >  Typescript error on computed array property: "Property 'map' does not exist on type &
Typescript error on computed array property: "Property 'map' does not exist on type &

Time:09-15

I have a computed property (array) which is taken from another computed property.

When trying to use map/filter/reduce/find on the property, it causes the linting error:

Property 'map' does not exist on type 'ComputedRef<any>

So how do I declare that computed property in the correct way? I'm using Vue 3 (composition api) with Typescript and Volar (for vscode).

const product = reactive({});            //<-- empty until it is loaded

const getItem = computed(() => {
  return items.map( (item:any) => {      //<-- typescript error
    return item;                   //(simplified code, returns 1 item in reality)
})

const items = computed(() => {
  return product?.items;                //<-- items array        
});

I also tried

const items = computed<any[]>(() => {

which causes the same error (on getItem function).

And this:

const items:any[] = computed<any[]>(() => {

which causes error on "items" that says Type 'ComputedRef<any>' is missing the following properties from type 'any[]': length, pop(..etc)

CodePudding user response:

Computed refs have a value prop that allow you to access the ref's, well, value.

So you would actually use it like this:

const product = reactive({});

const getItem = computed(() => {
  return items.value.map((item:any) => {
    return item;
  });
});

const items = computed(() => {
  return product?.items;     
});
  • Related