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[]