Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you type partial types in a TypeScript Angular application using an Apollo backend?

Edit: I'm looking for an authority and sourced answer from Graphql-Angular community to provide a best practice example.

For example, we have a Person type defined as such in TypeScript:

interface Person {
  firstName: string;
  lastName: string;
  birthDate: Date;
  age: number;
  ...and many more attributes
}

Let's say you have a component, and in accordance to the graphql mantra, you only fetch what you need. No overfetching and underfetching.

I only need the Person's firstName and age, so I make that in my Apollo Query.

Now, how do I type this Object that I just fetched?

The structure is a partial of Person, so I'm inclined to simply do Partial<Person>. This makes all the attributes declared on Person optional.

But that's not what's going on here. We're pulling a partial of Person with only age and firstName. That's it.

Is there no other way to type this correctly other than making another interface like:

interace MyComponentPerson {
  firstName: string;
  age: number;
}

Is there an official style guide / way to do this? I've asked on their slack and not getting answers. Looked on the docs as well didn't see anything about this.

like image 296
Ka Mok Avatar asked Nov 17 '22 04:11

Ka Mok


1 Answers

You could define:

type MyComponentPerson = Pick<Person, "firstName" | "age">;

If you want to automatically generate this type based on the query, something like Type gql-tag in TypeScript might work for you. If that solution isn't quite right, please provide an example of your query and I may be able to help.

like image 113
Matt McCutchen Avatar answered Nov 20 '22 00:11

Matt McCutchen