简体   繁体   English

Typescript 在 trpc 中重载未命名的 function

[英]Typescript overloading unnamed function in trpc

I have a typical trpc route.我有一条典型的 trpc 路线。 It fetches posts .它获取posts If there is an id argument, it fetches 1 post.如果有 id 参数,它会获取 1 个帖子。 If none, it fetches all posts.如果没有,它会获取所有帖子。 What is the syntax for overloading an unnamed function, and where do I put the overload code in this case?重载未命名的 function 的语法是什么,在这种情况下我应该把重载代码放在哪里?

publicProcedure
    .input(z.object({ id: z.string().nullish() }).nullish())
    .query(async ({ input }) => {

      const url = "https://example.com/posts";
      const json = (await got.get(url).json()) as IPosts[];

      if (input && input.id) {
        const posts = json.find(p => p.id === input.id);
        if (posts) return posts;
      }

      return json;
    })

Not sure if the below works or is the correct syntax but looking to put something like one of the below to overload the function不确定下面是否有效或者是正确的语法但希望放置类似下面的内容之一来重载 function

type IOverload = {
   (id: undefined): IPosts[];
   (id: string): IPost; 
}

// or

function unnamedFn<T extends string | null>(id: T): T extends string ? IPost : IPosts[]

Your first idea works fine !你的第一个想法很好!

type IPost = {};

type IOverload = {
    (id: undefined): IPost[];
    (id: string): IPost;
}

declare const overloaded: IOverload;

overloaded(undefined)
//^? IPost[]

overloaded('')
//^? IPost

Playground 操场

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

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