如何使用 Apollo 后端在 TypeScript Angular 应用程序中键入部分类型? [英] How do you type partial types in a TypeScript Angular application using an Apollo backend?

查看:23
本文介绍了如何使用 Apollo 后端在 TypeScript Angular 应用程序中键入部分类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找来自 Graphql-Angular 社区的权威和来源答案,以提供最佳实践示例.

例如,我们在 TypeScript 中定义了一个 Person 类型:

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
}

假设你有一个组件,根据 graphql 的口头禅,你只获取你需要的东西.没有过度获取和不足.

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

我只需要 PersonfirstNameage,所以我在我的 Apollo 查询中进行了设置.

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?

结构是Person的一部分,所以我倾向于简单地做Partial.这使得在 Person 上声明的所有属性都是可选的.

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.

但这不是这里发生的事情.我们拉取了一部分 Person,只有 agefirstName.就是这样.

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.

推荐答案

您可以定义:

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

如果您想根据查询自动生成此类型,例如 键入 gqlTypeScript 中的 -tag 可能对你有用.如果该解决方案不太正确,请提供您的查询示例,我可能会提供帮助.

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.

这篇关于如何使用 Apollo 后端在 TypeScript Angular 应用程序中键入部分类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆