我试图对trpc.useQuery的每一个电话都做一个包装器。它应该是这样的:
function wrapper(pathAndInput) {
const result = trpc.useQuery(pathAndInput)
/* some code that also uses `pathAndInput` */
return result
}但是,我不能让pathAndInput有一个可变的第二个元素这一事实。也就是说,在trpc.useQuery(["key", params], options)中,params部件是可选的。
到目前为止,我所拥有的类型是:
function useIndexedTRcpQuery<TRouteKey extends TQuery>(
pathAndInput: inferQueryInput<TRouteKey> extends (undefined | void | null)
? [TRouteKey]
: [TRouteKey, inferQueryInput<TRouteKey>]
): UseQueryResult<inferQueryOutput<TRouteKey>>但是,我得到了以下类型记录错误:
trpc.useQuery(pathAndInput) ^源有一个元素,但目标需要2个
我还尝试了以下几点:
function useIndexedTRcpQuery<TRouteKey extends TQuery>(
pathAndInput: [
key: TRouteKey,
args?: inferQueryInput<TRouteKey>,
],
): UseQueryResult<inferQueryOutput<TRouteKey>>这将产生以下错误:
trpc.useQuery(pathAndInput) ^源不提供对目标位置1处的变量元素的匹配。
将trpc.useQuery的第一个参数键入为泛型的正确方法是什么?
作为参考,下面是上面代码中的"utils类型“(非常标准的trpc内容):
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]>;发布于 2022-08-17 13:43:59
首先,您可以在trpc.ts文件中定义一个类型。(或者在您定义其他“相当标准的trpc内容”的地方)。
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来键入查询参数。
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-演示-应用程序。
https://stackoverflow.com/questions/73297051
复制相似问题