Home > other >  vue ref property not able to infer type correctly
vue ref property not able to infer type correctly

Time:11-14

Adding an extra property to an array of object in composeable method, but ts is complaining about the assignment, event the types are shown correctly

import { ref } from 'vue';

export const useActionLinks = <T extends { icon: string; text: string }>(
  data: T[]
) => {
  let active = '';

  function activeMapper(d: T) {
    return {
      ...d,
      isActive: d.text === active,
    };
  }
  const itemsData = data.map(activeMapper);

  const items = ref(itemsData);

  function onSetActive(text: string) {
    active = text;
    items.value = items.value.map(activeMapper); // Error: not assignable
  }

  // initial set first one
  if (items.value[0]) {
    items.value[0].isActive = true;
  }

  return {
    items,
    onSetActive,
  };
};

ts error on items.value = items.value.map(activeMapper); not assignable.

typescript-playground

CodePudding user response:

Based on this issue comment :

When using ref or reactive with generics you need to cast to as Ref<T> and as reactive<T> if you sure that the type doesn't have any nested refs, because ref and reactive will unwrap nested refs automatically

   import {ref, Ref} from 'vue';
  // ... 
   const items = ref(itemsData) as Ref<T[]>;
  • Related