ckastbjerg / next-type-safe-routes

Never should your users experience broken links again!
MIT License
70 stars 5 forks source link

A simpler API using template literals may be possible #21

Open osdiab opened 3 years ago

osdiab commented 3 years ago

In TypeScript, you can use template literal types for strings:

type UserRoutePath = `/users/${string}`;
type UserLikesRoutePath = `/users/${string}/likes`;
type TeamRoutePath = `/teams/${string}`;
type Routes = UserRoutePath | UserLikesRoutePath | TeamRoutePath;

This library, rather than using a special object type, can probably just create a mega union of strings that just includes all the routes. The main downside is just that there isn't really a way as far as I know to make a type for "a string that doesn't have a / in it" so it's possible you'd actually make a bad route path, but that's unlikely.

I also personally think this library can just stop dealing with query params (since it doesn't actually deal with anchors either anyway) which would contain the scope of the library.

ckastbjerg commented 3 years ago

That would be cool!

I actually explored this a bit when creating the library. And as I recall it, template literals support had just come out at the point. But it was my understanding, that it would only work for predefined strings, e.g:

type World = "world";
type Greeting = `hello ${World}`;

But if it can be used as you describe, it would simplify things a lot yes :)

osdiab commented 3 years ago

yep it does - i can draft a PR to show what that'd look like :) though that said there are benefits to the current system, specifically that the parameters are named so you're less likely to get it wrong for a path that has multiple params. just less natural

ckastbjerg commented 3 years ago

If you think it's somewhat fast to do, I would be very interested to see an experiment with this, yes :) And as you've already touched upon, it would be interesting to see:

Also, sorry if I'm a bit slow to response 🤷 I'm a bit busy with my day job and two small kids at home at the moment ;)

osdiab commented 3 years ago

No worries on timing, my life is hectic too :) I'll try to put something together!