简体   繁体   English

获取typescript类型的trpc或react-query的useQuery结果“data”属性

[英]Obtaining typescript type of trpc or react-query's useQuery result "data" property

In my React + TRPC application, I call const { data: promotion } = trpc.promotions.getPromotion.useQuery({ id: promotionId }) in the client-side.在我的 React + TRPC 应用程序中,我在客户端调用const { data: promotion } = trpc.promotions.getPromotion.useQuery({ id: promotionId }) promotion 's type is detected by looking at the return type of the actual server-side code:通过查看实际服务器端代码的返回类型来检测promotion的类型:

  getPromotion: protectedProcedure
    .input(z.object({ id: z.string() }))
    .query(async({ ctx, input }) => {
      const promotion = await ctx.prisma.promotion.findUniqueOrThrow({
        where: {
          id: input.id
        }
      })

      return {
        ...promotion,
        canModify: false
      }
    })

However, I want to use this same type in an interface another component:但是,我想在另一个组件的接口中使用相同的类型:

interface Example {
   promotion: TheDetectedTypeOfGetPromotionReturn??
}

The problem is, I can't find a way to "extract" the type I need.问题是,我找不到一种方法来“提取”我需要的类型。

I thought maybe I could use ReturnType<typeof trpc.promotions.getPromotion.useQuery>['data'] but that just returns unknown .我想也许我可以使用ReturnType<typeof trpc.promotions.getPromotion.useQuery>['data']但这只会返回unknown Yet, data is a valid type on the returned object.然而,数据是返回的 object 的有效类型。

Here's where the useQuery code is defined: https://github.com/trpc/trpc/blob/9e84d4d9c43de3272aa84bf4110e31e47dc5dda6/packages/react-query/src/shared/hooks/createHooksInternal.tsx#L427这是定义 useQuery 代码的地方: https://github.com/trpc/trpc/blob/9e84d4d9c43de3272aa84bf4110e31e47dc5dda6/packages/react-query/src/shared/hooks/createHooksInternal.tsx#L427

Here's the query base type it uses from react-query: https://github.com/TanStack/query/blob/1614c31f84744c62b5bee8f2ff97fc15a1652e86/packages/query-core/src/types.ts#L367这是它从 react-query 使用的查询基本类型: https://github.com/TanStack/query/blob/1614c31f84744c62b5bee8f2ff97fc15a1652e86/packages/query-core/src/types.ts#L367

I managed to do it like this我设法这样做了

import {type UseTRPCQueryResult} from '@trpc/react query/shared'
import {type inferRouterOutputs} from '@trpc/server'
import {type TRPCClientErrorLike} from '@trpc/react-query'

type YourType = UseTRPCQueryResult<inferRouterOutputs<AppRouter>['promotions']['getPromotions'], TRPCClientErrorLike<AppRouter>>['data']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM