Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to narrow Typescript Types autogenerated by graphQL codegen?

I get a TypeScript type autogenerated from AWS-Amplify GraphQL (which uses apollo-codegen I believe) like such:

export type GetNoteQuery = {
  getNote:  {
    __typename: "Note",
    id: string,
    createdAt: string | null,
    updatedAt: string | null,
    title: boolean | null,
    content: string | null,
  } | null,

I want to generate a base type of "Note" to use as "base" type to use in my code when using the returned data. I.e. mapping notes onto a React component, etc.

Is there a way to narrow this type that is auto generated, or to extend it in some way, to have it look like:

type Note = {
    id: string,
    createdAt: string | null,
    updatedAt: string | null,
    title: boolean | null,
    content: string | null
}

like image 755
Stephen A. Lizcano Avatar asked Nov 03 '19 18:11

Stephen A. Lizcano


People also ask

What does CodeGen do GraphQL?

GraphQL-CodeGen is a CLI that can generate code from your GraphQL operations and schema. In React projects using typescript operations, it is very helpful to map GraphQL schema into interfaces. GraphQL can also generate hooks from operations.

How do you use Apollo CodeGen?

Apollo's GraphQL CodegenDownload any GraphQL schema using a GraphQL endpoint. Generate TypeScript types for queries written in an Apollo Client project (given a valid GraphQL schema)


1 Answers

You can use an index query to get the type of getNote coupled with Exclude to get rid of the the null from the property type. You then can use Omit to get rid of the extra property.

export type GetNoteQuery = {
  getNote: {
    __typename: "Note",
    id: string,
    createdAt: string | null,
    updatedAt: string | null,
    title: boolean | null,
    content: string | null,
  } | null
}

type Note = Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'>

You can also use an interface to get a stronger name for the type:


interface Note extends Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'> { }


like image 200
Titian Cernicova-Dragomir Avatar answered Nov 15 '22 08:11

Titian Cernicova-Dragomir