MY CURRENT DILEMMA:
In my quest to seamlessly integrate vue-apollo v4 with Typescript, I have encountered a challenge.
I am in the process of retrieving data from a simple query using useQuery along with useResult.
The default return type of useResult is:
Readonly<Ref<Readonly<any>>>
SNEAK PEEK AT THE CODE:
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
}
}
INITIAL ATTEMPT:
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)
SECOND ATTEMPT:
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)
THIRD ATTEMPT:
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)
FOURTH ATTEMPT:
Following insights from @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...
FIFTH ATTEMPT:
After refining advice received from @tony19
// QUERY - simplified
export const GET_COUNTRY = gql`
query getCountry($code: ID!) {
country(code: $code) {
code
name
}
}
`
// TYPES - simplified
export interface Country {
code: string,
name: string
}
export type CountryQuery = {
country: Country
}
const { result, loading } = useQuery<CountryQuery>(GET_COUNTRY, {code: code});
const country = useResult(result, {}, (data) => data.country);
A warning message pops up in vsCode:
Property 'name' does not exist on type 'Readonly<{}>'.
ANOTHER TWIST TO THE FIFTH ATTEMPT:
In line with @tony19's guidance, making some adjustments:
type CountryQuery = {
getCountry: Country
}
This leads to an error:
Property 'country' does not exist on type '{ getCountry: { code: string; name: string; }; }'
THE BIG QUESTION:
Can I successfully merge useResult with my custom Typescript utilities and eliminate these compatibility issues?