Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(router): add req.params type-safety via string patterns; #16

Merged
merged 1 commit into from
Mar 24, 2021

Conversation

lukeed
Copy link
Owner

@lukeed lukeed commented Mar 24, 2021

Shoutout to @dummdidumm for reminding me!

TypeScript Playground

Note: There's still a TODO for wildcard patterns (/foo/*, /:foo/*, /:foo/*/:bar) but this can come later.

@lukeed lukeed merged commit b048388 into master Mar 24, 2021
@lukeed lukeed deleted the types/params branch March 24, 2021 22:04
@dummdidumm
Copy link
Contributor

dummdidumm commented Mar 25, 2021

Thanks for the shoutout 😄

Regarding the TODO: I solved it this way: Playground

type RouteParams<T extends RoutePattern> =
	T extends `${infer Prev}/*/${infer Rest}`
		? { wild: string } & RouteParams<Prev> & RouteParams<Rest>
  : T extends `${string}:${infer P}?/${infer Rest}`
		? { [K in P]?: string } & RouteParams<Rest>
  : T extends `${string}:${infer P}/${infer Rest}`
		? { [K in P]: string } & RouteParams<Rest>
  : T extends `${string}:${infer P}?`
		? { [K in P]?: string }
  : T extends `${string}:${infer P}`
		? { [K in P]: string }
  : T extends `${string}*`
		? { wild: string }
  : {};

Changes are

  • remove the unnecessary infers and replace it with {string}
  • for the wildcard, do a recursion before and after the /*/. Problem is, if you don't do this, TS will just go greedy up until the first * and discard everything before that. This fixes the missing foo comments in the Playground
  • make the optional param recursion the same as the one with required params, not sure why it was like this in the original Playground. This fixes the baz must be baz? comment

@lukeed
Copy link
Owner Author

lukeed commented Mar 25, 2021

@dummdidumm This is awesome!! Thanks!
TIL that {string} can be used for inference. Dunno why never tried that 😅

lukeed pushed a commit that referenced this pull request Mar 25, 2021
* feat(router): add wildcard to string patterns
* chore: swap merge order
* chore: add type-check assertions

Related #16
Co-authored-by: Luke Edwards <luke.edwards05@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants