如何使用Apollo后端在TypeScript Angular应用程序中键入部分类型? [英] How do you type partial types in a TypeScript Angular application using an Apollo backend?
问题描述
我正在寻找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.
我只需要Person
的firstName
和age
,所以我在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>
.这使得在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.
但这不是这里发生的事情.我们只用age
和firstName
拉一部分Person
.就是这样.
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">;
如果您要基于查询自动生成此类型,请类似类型gql TypeScript中的-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屋!