Skip to content

Instantly share code, notes, and snippets.

@jakobvase
Created December 20, 2022 18:53
Show Gist options
  • Save jakobvase/612e968fe05d8d62300b61e9def4f000 to your computer and use it in GitHub Desktop.
Save jakobvase/612e968fe05d8d62300b61e9def4f000 to your computer and use it in GitHub Desktop.
Some thoughts on router types
**
* A router needs to accept adding RouteDefinitions, which are routes with a name and
* path, and potentially a 'fromArgs' and 'fromUrl' constructor, however these might be
* possible to determine programmatically, so maybe not necessary.
*
* Uses:
* * Determine which route we are on, and get any arguments for that route.
* * Create a link to a route by supplying name and arguments.
* * Potentially extend the route definition to do more? Preload? Do we want that in by default?
*/
type ArgsFromPath<TPath extends string> = Record<TPath, string>;
type RouteDefinition<
TName extends string = string,
TPath extends string = string
> = {
name: TName;
path: TPath;
fromArgs: (args: ArgsFromPath<TPath>) => RouteInstantiation<TName, TPath>;
fromUrl: (url: string) => RouteInstantiation<TName, TPath>;
};
type RouteInstantiation<TName extends string, TPath extends string> = {
name: TName;
path: TPath;
url: string;
args: ArgsFromPath<TPath>;
};
type Subscriber = (a: RouteInstantiation<string, string>) => void;
export type Router = {
currentRoute: RouteInstantiation<string, string>;
push: (route: RouteInstantiation<string, string>) => void;
addRoutes: (...newRoutes: readonly RouteDefinition[]) => Router;
removeRoutes: (...routeNames: readonly string[]) => Router;
subscribe: (subscriber: Subscriber) => () => void;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment