简体   繁体   中英

How to add type to graphql schema using react and typescript?

i have a query like below

query MyQuery($id: ID!) {
    something(id: $id) {
        details {
            id
            name
        }
    }
}

and in the types.graphql i have

type something {
    details: // this should either type details1 or type details2 
}

type details1 {
    id: string
    name: string
    description: string
}

type details2 {
    id: string
    name: string
    description: string
    other: string!
}

so the type details can be either of type details1 or details2

how can i specify that in the type something for details field.

could someone help me with this. thanks.

EDIT:

i have tried something like below

type something {
    details : details1 | details2;
}

but this doesnt work.

what i can possibly do is create another type

type details3 {
    id: string
    name: string
    description: string
    other: string
}

which is a combination of details2 and details3

and use it like

type something {
    details: details3
}

but dont want to do so.

I think you missed the = symbol when defining a type, I've just tried this and it worked:

type details1 = {
    id: string
    name: string
    description: string
}

type details2 = {
    id: string
    name: string
    description: string
    other: string
}

type something = {
  details: details1 | details2;
}

const test: something = {
  details: {
    id: 'abc',
    name: 'abc',
    description: 'abc',
  }
}


const test2: something = {
  details: {
    id: 'abc',
    name: 'abc',
    description: 'abc',
    other: 'abc'
  }
}

use a union

type something {
    details : details;
}

union details = details1 | details2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM