Skip to content
This repository has been archived by the owner on May 3, 2024. It is now read-only.

fix: PathParams type #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 28 additions & 14 deletions lib/middleware/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,34 @@ export type RouteHandlerMatch<S extends string> = {
matches?: RegExpExecArray;
} & Route<Handler<PathParams<S>>>;

export type SplitRoute<S extends string> = string extends S ? string[]
: S extends `${infer Start}/:${infer Param}/${infer Rest}`
? [Param, ...SplitRoute<Rest>]
: S extends `${infer Start}/:${infer Param}+` ? [Param]
: S extends `${infer Start}/:${infer Param}` ? [Param]
: [];

export type PathParams<S extends string> =
& {
[P in SplitRoute<S>[number]]: string;
}
& {
[P in SplitRoute<S>[number]]?: string;
};
/** Split type `"one/:two/:three?/:four"` into `["one", ":two", ":three?", ":four"]` */
type SplitPath<S extends string> =
string extends S ? string[] :
S extends `${infer A}/${infer B}` ? [A, ...SplitPath<B>] :
[S];

/** Convert type `"one" | ":two" | ":three?" | ":four"` into `"two" | "four"` */
type ExtractRequiredParams<S extends string> =
string extends S ? string :
S extends `:${infer A}?` ? never :
S extends `:${infer A}` ? A :
never;

/** Convert type `"one" | ":two" | ":three?" | ":four"` into `"three"` */
type ExtractOptionalParams<S extends string> =
string extends S ? string :
S extends `:${infer A}?` ? A :
never;

/**
* Convert a route path string literal type such as "one/:two/:three?/:four"
* into a params interface like `{ two: string; three?: string; four: string }`
*/
export type PathParams<S extends string> = {
[P in ExtractRequiredParams<SplitPath<S>[number]>]: string;
} & {
[P in ExtractOptionalParams<SplitPath<S>[number]>]?: string;
};

/**
* Router wraps the tiny-request-router `Router` with a more strict RouteHandler type and automatic params typings.
Expand Down