首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >包装器钩子的trpc.useQuery第一个参数的确切类型

包装器钩子的trpc.useQuery第一个参数的确切类型
EN

Stack Overflow用户
提问于 2022-08-09 19:20:49
回答 1查看 949关注 0票数 0

我试图对trpc.useQuery的每一个电话都做一个包装器。它应该是这样的:

代码语言:javascript
复制
function wrapper(pathAndInput) {
  const result = trpc.useQuery(pathAndInput)
  /* some code that also uses `pathAndInput` */
  return result
}

但是,我不能让pathAndInput有一个可变的第二个元素这一事实。也就是说,在trpc.useQuery(["key", params], options)中,params部件是可选的。

到目前为止,我所拥有的类型是:

代码语言:javascript
复制
function useIndexedTRcpQuery<TRouteKey extends TQuery>(
    pathAndInput: inferQueryInput<TRouteKey> extends (undefined | void | null)
        ? [TRouteKey]
        : [TRouteKey, inferQueryInput<TRouteKey>]
): UseQueryResult<inferQueryOutput<TRouteKey>>

但是,我得到了以下类型记录错误:

trpc.useQuery(pathAndInput) ^源有一个元素,但目标需要2个

我还尝试了以下几点:

代码语言:javascript
复制
function useIndexedTRcpQuery<TRouteKey extends TQuery>(
    pathAndInput: [
        key: TRouteKey,
        args?: inferQueryInput<TRouteKey>,
    ],
): UseQueryResult<inferQueryOutput<TRouteKey>>

这将产生以下错误:

trpc.useQuery(pathAndInput) ^源不提供对目标位置1处的变量元素的匹配。

trpc.useQuery的第一个参数键入为泛型的正确方法是什么?

作为参考,下面是上面代码中的"utils类型“(非常标准的trpc内容):

代码语言:javascript
复制
import type { UseQueryResult } from "react-query";
import type { inferProcedureOutput, inferProcedureInput } from "@trpc/server";

type TQuery = keyof AppRouter["_def"]["queries"];

type inferQueryInput<
  TRouteKey extends TQuery,
> = inferProcedureInput<AppRouter["_def"]["queries"][TRouteKey]>;

type inferQueryOutput<
  TRouteKey extends TQuery,
> = inferProcedureOutput<AppRouter["_def"]["queries"][TRouteKey]>;
EN

回答 1

Stack Overflow用户

发布于 2022-08-17 13:43:59

首先,您可以在trpc.ts文件中定义一个类型。(或者在您定义其他“相当标准的trpc内容”的地方)。

代码语言:javascript
复制
export type TUseQuery = [
  TQuery, // we use the already existing TQuery type which holds all possible querys
  Record<string, any> // We use a Record to type the Object consisting of keys in the form of strings and any possible input.
];

之后,我们可以使用Type来键入查询参数。

代码语言:javascript
复制
import { trpc, TUseQuery } from "../utils/trpc"; // path to your trpc file

let query: TUseQuery= [
    "example.hello", // trpcQuery
    { text: "from tRPC" }, // trpcQuery Input Object
] 

function laodData(query: TUseQuery) : UseQueryResult {
  return trpc.useQuery(query) 
}

console.log(laodData(query));

你瞧。

PS:测试在T3-演示-应用程序。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73297051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档