简体   繁体   中英

Typescript overloading unnamed function in trpc

I have a typical trpc route. It fetches posts . If there is an id argument, it fetches 1 post. 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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