Typescript pattern for handling URL search param as a specific ID Type
Hello everyone
I'm working on a project where I use URL to manage the state of a document by storing the ID in the search params and retrieve it using nextJs's useSearchParams hook. Typescript correctly recognizes it as string by default.
I plan on passing the ID to a function who's validators expect the variable to be the correct Document Id. Could anyone share the best pattern on how to properly cast or validate the search param so that it matches the expected type?
4 Replies
mySearchParam as Id<"myTable">
I'll make sure to add this pattern here (you can see how to get Id
on this page):
https://docs.convex.dev/typescript#writing-frontend-code-in-typescriptTypeScript | Convex Developer Hub
Move faster with end-to-end type safety.
Thanks! Yes, it would be helpful to add it the typescript doc page.
https://docs.convex.dev/database/document-ids#serializing-ids touches on this too.
Another variant if you want custom behavior when the string is not a valid ID (e.g. redirect) is to type your Convex function as accepting a string and use
db.normalizeId
to check that it's the expected type, throwing a ConvexError
if not. I have an app using this pattern to redirect to a home page when the ID in the URL is invalid.Document IDs | Convex Developer Hub
Create complex, relational data models using IDs.
Thank you. That was going to be my follow up question, i.e. how to ensure that the string is indeed an Id. ctx.db.normalizeId works well for my usecase