Brand RouteUrl type to distinguish it from plain strings#877
Brand RouteUrl type to distinguish it from plain strings#877bakerkretzmar merged 3 commits intotighten:2.xfrom
Conversation
RouteUrl was a plain alias for `string`, so there was no type-level distinction between a URL produced by `route()` and any arbitrary string. Now RouteUrl is a branded type: it's still assignable to `string`, but a plain `string` can't be assigned to `RouteUrl` without going through `route()`.
|
Very cool. Re-explaining your code example for my own understanding, and for when I inevitably come back to this to remind myself how it works: now, anything explicitly typed as Thanks! |
Exactly, that way you can validate that your variable must be a validated RouteUrl. This is useful for Link components or custom fetch functions for example. |
|
Thanks for the merge :) |
Summary
The
RouteUrlbranded type I added a while ago used a plain alias. I've since learned that using aunique symbolis the recommended approach, so this PR improves the branding.RouteUrluses aunique symbolbrand — still assignable tostring, but a plainstringcan't be assigned toRouteUrlRouteUrlWhy
unique symbol?Using
unique symbolas the brand key is the recommended pattern for branded types in TypeScript because:declare constonly exists in the type systemSee also: Preventing Accidental Interchangeability in TypeScript
Example
Test plan
@ts-expect-errortest confirms a plainstringis not assignable toRouteUrlnpx vitest --typecheck)