【发布时间】:2022-01-23 15:47:09
【问题描述】:
情况:
我正在尝试将 vue-apollo v4 与 Typescript 集成。
我正在使用useQuery 和useResult 获取一个简单的查询。
useResult 默认返回此类型:Readonly<Ref<Readonly<any>>>
代码:
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