如何使用 TypeScript 处理 Vue 组合 api 中的 UnwrapRefSimple

Hen*_*Jan 3 typescript vue.js typescript-typings vue-composition-api

当使用响应式对象 Vue 组合 api 时,我收到有关 的 Typescript 错误UnwrapRefSimple<T>
在 内部使用数组时尤其如此ref()

一个例子。

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,
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

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>'
Run Code Online (Sandbox Code Playgroud)

我尝试过添加UnwrapRef到代码中:

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>'
Run Code Online (Sandbox Code Playgroud)

但随后代码中的其他地方会出现问题,而且这会变得难以阅读。
有谁知道如何很好地处理这个问题?

小智 7

const groupsArray = ref<T[]>([]) as Ref<T[]>
Run Code Online (Sandbox Code Playgroud)

请参阅:https ://github.com/vuejs/core/issues/2136#issuecomment-908269949

  • 通过额外的支持信息可以改进您的答案。请[编辑]添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以[在帮助中心](/help/how-to-answer)找到有关如何写出好的答案的更多信息。 (3认同)