英文:
Prisma/React Query Dependent undefined type challenges
问题
我想将一个查询的输出(Prisma上的TRPC查询)用作将来查询的依赖输入。
我按照React Query的依赖文档进行操作,但遇到了类型错误,第一个查询的返回可能为undefined(例如,product is possibly 'undefined'
):
const { data: product } = api.product.getUnique.useQuery({ id: pid });
const options = api.option.getAll.useQuery(
{
product: product.productSize,
region: product.productRegion,
},
{ enabled: !!product }
);
包含enabled的情况不已经处理了吗?如果没有,那么在Typescript中适应的正确方法是什么。
英文:
I would like to take the output of one query (a TRPC query on Prisma) and use this as the dependent input in a future query.
I followed the dependent documentation for React Query but running into type errors that the return of the first may possibly be undefined (e.g. product is possibly 'undefined'
):
const { data: product } = api.product.getUnique.useQuery({ id: pid });
const options = api.option.getAll.useQuery(
{
product: product.productSize,
region: product.productRegion,
},
{ enabled: !!product }
);
Does the inclusion of enabled not already handle this? If not, what is the correct way to adapt for Typescript.
答案1
得分: 1
只需将product
值转换为布尔值返回任何真值(例如,如果product
等于{}
,它仍将返回true
,这意味着product
不一定具有productSize
或productRegion
属性,我会首先更改它为:
{ enabled: !!product && product.productSize && product.productRegion }
如果这不能解决TypeScript错误,作为开发人员,您可以确定这些值确实存在,因此可以使用TypeScript中的as
关键字告诉它您确切知道类型是您想要的:
(在此示例中,我假设这些值是字符串,但您可以将其更改为数字或它们的真实值)
const options = api.option.getAll.useQuery(
{
product: product.productSize as string,
region: product.productRegion as string,
},
{ enabled: !!product && product.productSize && product.productRegion }
);
英文:
Just casting the product
value as a boolean return any truthy value (f.e if product
will be equal to {}
it will still result in true
, that means that product
won't necessarily have the productSize
or productRegion
properties, I would change it first to:
{ enabled: !!product && product.productSize && product.productRegion }
If that doesn't fix the typescript error, you as a developer can know for sure that the values are actually there so what you can use the as
keyword in typescript to tell it that you know for sure that the type is what you want it to be:
(In this example I assumed that the values are string but you can change it to number or whatever the true value of them are)
const options = api.option.getAll.useQuery(
{
product: product.productSize as string,
region: product.productRegion as string,
},
{ enabled: !!product && product.productSize && product.productRegion }
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论