0

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[]
wongz
  • 3,255
  • 2
  • 28
  • 55

1 Answers1

0

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

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134