Closed geon closed 6 years ago
I tried implementing this in your library, but it was not clear how I could do it. If you have suggestions for implementing a parse
function, I'd be interested.
Hey @geon - I think the short answer is that you can't really implement that in this library.
When we were writing this lib we actually started going down this path a bit just with numeric path params. However, we came to the conclusion that we wanted to stick to flat string / string interfaces for describing our routing.
Ultimately, path params are strings. Mapping them to any other type is a serialization problem, which means you have to deal with everything that comes along with serialization problems. Namely, what happens if it fails?
React Router made the decision to pass this problem off the application, and we are pretty much mirroring that decision (ie their examples where they parse integer values out of path param matches). Our main objective with this lib was:
/view/:id
) and a corresponding interface representing the required params ({id: string}
). id
param that I don't have to depend on keeping in sync by convention.match.params
That's pretty much it. Obviously the problem of parsing route params is a real thing, but its out of scope for what we are trying to do in this lib.
Thanks a lot for sharing your work and idea with us, btw. I like the breadcrumbs idea quite a bit, and that might be something we consider incorporating.
Hi!
I had a need for this kind of type safe routing a coupe of months ago. I didn't find any library, so I implemented my own. The basic idea is very similar to yours, but has some pros and cons.
https://github.com/geon/routes/blob/master/usage.ts
Typed Params
Most importantly, my routes has properly typed params, not just named strings. I do this by passing a
parse
function to the route creator. This function converts a{[paramName: string]: string}
to a type object of typeTParams
.The parameters are also validated. They can be checked to conform to some regex, or checked to exist in an array, etc.
The output-ed typed params object does not need to have the same number of properties ar the input. Properties like
pageNumber
andpageSize
can be lumped together into apagination
object.This was invaluable when developing our app.
Crumbs
A minor but neat feature I implemented was bread crumb generation. Each route has a function that takes params and returns a title string. Optionally, it also has a previous page route. Using this, we can easily generate an array of titles + hrefs, that can be rendered as a bread crumb.