【问题标题】:vue-apollo - Property 'value' does not exist on type 'Readonly<Ref<Readonly<any>>>'vue-apollo - 类型“Readonly<Ref<Readonly<any>>>”上不存在属性“值”
【发布时间】:2022-01-23 15:47:09
【问题描述】:

情况:

我正在尝试将 vue-apollo v4 与 Typescript 集成。

我正在使用useQueryuseResult 获取一个简单的查询。

useResult 默认返回此类型:Readonly&lt;Ref&lt;Readonly&lt;any&gt;&gt;&gt;

代码:

import { GET_COUNTRY } from '../graphql/queries'
import { Country } from '../types'

setup() {
  const route = useRoute()
  const code = route.params.code

  const { result, loading } = useQuery(GET_COUNTRY, {code: code}, { 
    clientId: 'default', 
    fetchPolicy: 'cache-first'
  });
  const country = useResult(result, {}, (data) => data.country);

  console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

  return {
    country,
    loading
  }
}

尝试 1:

const country: Country = useResult(result, {}, (data) => data.country);
// Type 'Readonly<Ref<Readonly<any>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

尝试 2:

const country = useResult(result, {}, (data) => data.country as Country);
console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

尝试 3:

const country: Country = useResult(result, {}, (data) => data.country as Country);
// Type 'Readonly<Ref<Readonly<Country | {}>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

尝试 4: 经过@tony19 的反馈

const { result, loading } = useQuery<Country>(GET_COUNTRY, {code: code});
const country = useResult(result, {}, (data) => data.country);
// Property 'country' does not exist on type '{ native: string; phone: string; capital: string; currency: string...

问题:

是否可以将 useResult 与我自己的 Typescript interface 结合使用?

【问题讨论】:

    标签: javascript typescript vue.js vuejs3 vue-apollo


    【解决方案1】:

    假设有以下几种:

    type Country = {
      name: string
    }
    
    const GET_COUNTRY = gql`
      query GetCountry {
        getCountry {
          name
        }
      }
    `
    

    应键入结果以匹配GET_COUNTRY 查询:

    type CountryQuery = {
      getCountry: Country
    }
    

    然后,将该查询类型指定为useQuery() 的类型参数:

    const { result, loading } = useQuery<CountryQuery>(GET_COUNTRY, ⋯)
                                            ?
    

    resultcountryrefs,因此要访问基础数据,请使用 .value 解包:

    const country = useResult(result, {}, (data) => data.getCountry.name);
    console.log(country.value);
                          ?
    

    demo

    【讨论】:

    • @FrancescoMussi 固定答案;查看演示链接
    猜你喜欢
    • 2019-09-23
    • 2020-11-07
    • 2020-01-24
    • 2022-10-16
    • 2019-12-11
    • 2020-11-29
    • 1970-01-01
    • 2018-10-11
    • 2021-01-11
    相关资源
    最近更新 更多