0

I'm trying to type partial objects from GraphQL queries. In particular, I'm having trouble with an object similar to as follows ...

// Typescript types

interface Foo {
  bar: Bar
}

interface Bar {
  a: number,
  b: number
}

// GrapQL query

foo {
  bar {
    a
    // Note missing 'b' property
  }
}

When I pcome to type this response I can use Pick on the Bar property, but this then violates Foos declaration. I could create an entire new type but in my actual axample both Foo and Bar are complex objects - is there an easier way to type the result? How do people normally type GraphQL results?

1
  • asking for one field doesn't mean 2nd doesn't exist Commented Jun 7, 2021 at 8:47

1 Answer 1

1

i would recommend to use some existing package that can generate that types for you. eg gql code generator

otherwise easy way to avoid this type is to create partial types within whole object tree

interface Foo {
    bar: Bar;
}

interface Bar {
    a: number;
    b: number;
}

type partial<T extends object> = {
    [K in keyof T]?: T[K] extends object ? partial<T[K]> : T[K] 
}

const partialFoo: partial<Foo> = {
    bar: {
        a: 1
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.