Interface
This example shows how to work with interface types.
ts
// Our website uses Vitepress+Twoslash. Twoslash does not discover the generated Graffle modules.
// Perhaps we can configure Twoslash to include them. Until we figure that out, we have to
// explicitly import them like this.
import './graffle/modules/global.js'
// ---cut---
import { Graffle } from './graffle/$.js'
const pokemon = Graffle.create()
const beings = await pokemon.query.beings({
__typename: true,
id: true,
name: true,
___on_Patron: {
//^^^^^^^^^^^^
money: true,
},
___on_Trainer: {
//^^^^^^^^^^^^^
class: true,
},
___on_Pokemon: {
//^^^^^^^^^^^^^
type: true,
},
})
// The following contrived switch console.logs how the returned type is a discriminated union.
// After checking the __typename, the type is known to be one of the three possible types
// and TypeScript narrows accordingly.
for (const being of beings) {
console.log(being.name)
switch (being.__typename) {
case `Patron`:
console.log(being.money)
break
case `Trainer`:
console.log(being.class)
break
case `Pokemon`:
console.log(being.type)
break
}
}Outputs
txt
Sallytxt
1080000txt
Dylantxt
3530000txt
Ashtxt
youthtxt
Mistytxt
teamRocketGrunttxt
Brocktxt
youthtxt
Garytxt
youthtxt
Pikachutxt
electrictxt
Charizardtxt
firetxt
Squirtletxt
watertxt
Bulbasaurtxt
grasstxt
Caterpietxt
bugtxt
Weedletxt
bug