typed-routes
Routes with TypeScript support.
This library is intended solely to help with pattern matching path-like strings. It makes no assumptions about location or browser history or any attempt to implement actual route change detection.
Usage
; // Like "/data/profiles/:userId/info" in Express .extend"data", "profiles" .param"userId" .extend"info";
Typed routes can be matched against strings to return the extracted params (if there's match) or to convert a params object to a param string
path.match"/data/profiles/xyz/info"; // => { userId: "xyz" }path.match"/daat/profylez/xyz/info"; // => undefined
Typed routes can also convert a set of params to a string route.
path.from; // => "/data/profiles/xyz/info"path.from; // => Type error
Routes may have optional types and rest types as well
;path.match"/gid/uid/a/b/c"; // => { groupId: "gid", userId: "uid", rest: ["a", "b", "c"] }path.match"/gid"; // => { groupId: "gid", rest: [] }
Routes can specify types.
; ;path.match"/profile/123"; // => { uid: 123 }path.match"/profile/abc"; // => undefined path.from; // => "/profile/123"path.from; // => Type error
Types are just an object with parse and stringify functions. For example,
this is the definition of the DateTimeParam
type, which converts a Date
to milliseconds since epoch.
;
You can provide your own types for more customized behavior (such as returning a default value is one is undefined).
API
createRoute
createRoute: Route;
Creates a route object with certain settings.
Route.extend
route.extend...parts: string: Route;
Adds static segments to route that must match exactly.
Route.param
route.paramname: string, type: ParamType = StringParam: Route;
Add a required parameter and optional type.
Route.opt
route.optname: string, type: ParamType = StringParam: OptRoute;
Add an optional parameter and type. .extend
and .param
cannot follow
a .opt
command.
Route.rest
route.resttype = StringParam: Route;route.restname = "rest", type = StringParam: Route;
Add a field that captures multiple parts of the path as an array. Defaults
to using rest
as the property but this can be changed. Type specifies
what kind of array we're working with (e.g. use IntParam
or FloatParam
to type as number[]
).
Built-In Param Types
-
StrParam
- Default parameter. Types as string. -
IntParam
- Type as integer usingparseInt
. -
FloatParam
- Type as float usingparseFloat
. -
DateTimeParam
- Type as Date by serializing as milliseconds since epoch. -
ArrayParam(ParamType, delimiter = ",")
- A function that takes another param type and returns as param type that parses as an array of the original type. For instance,ArrayParam(IntParam, "::")
will parse1::2::3
as[1, 2, 3]
.