Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle UnwrapRefSimple in Vue composition api with TypeScript

When using reactive objects Vue composition api I get Typescript errors about UnwrapRefSimple<T>.
This seems specifically the case when using arrays inside ref().

An example.

interface Group<T> {
  name: string
  items: T[]
}

export function useSomething<T extends object>({ model }: { model: T }) {

  const groupsArray = ref([] as Group<T>[])

  const group = {
    name: 'someGroup',
    items: [model],
  }

  groupsArray.value.push(group) // <-- this line is the problem

  return {
    groups: groupsArray,
  }
}

The error I get is:

Argument of type '{ name: string; items: T[]; }' is not assignable to parameter of type '{ name: string; items: UnwrapRefSimple<T>[]; }'.
  Types of property 'items' are incompatible.
    Type 'T[]' is not assignable to type 'UnwrapRefSimple<T>[]'.
      Type 'T' is not assignable to type 'UnwrapRefSimple<T>'.
        Type 'object' is not assignable to type 'UnwrapRefSimple<T>'

I've tried things like adding UnwrapRef to the code:

import { UnwrapRefSimple } from "@vue/composition-api"
...
items: UnwrapRefSimple<T[]>

But then problems pop up elsewhere in the code and besides, this becomes difficule to read.
Does anyone know how to handle this nicely?

like image 544
Hendrik Jan Avatar asked Sep 17 '25 14:09

Hendrik Jan


1 Answers

const groupsArray = ref<T[]>([]) as Ref<T[]>

see: https://github.com/vuejs/core/issues/2136#issuecomment-908269949

like image 57
prokhn Avatar answered Sep 19 '25 08:09

prokhn