#Typescript pattern for handling URL search param as a specific ID Type

4 messages · Page 1 of 1 (latest)

glad wolf
#

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?

warped kayak
glad wolf
#

Thanks! Yes, it would be helpful to add it the typescript doc page.

cloud ledge
#

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.

Create complex, relational data models using IDs.