ui-router-registry
v0.5.0
Published
Typed state names and params for UI-Router: a types-only registry for @uirouter/core
Readme
ui-router-registry
A types-only registry for typed routes — state names and params — on a UI-Router (@uirouter/core) router, inferred from the app's own as const state declarations. It emits no JavaScript.
Installation
npm install --save-dev ui-router-registryFeatures
RegisteredStatesandStatesOf: the interface each module augments with its ownas conststate declarations, keyed by name.Registertakes every declaration at one site instead, and the registry reads both. Until an app registers, every type below falls back to core'sstringandRawParams, so existing calls compile unchanged.AssertNoCollisionsandCollisionsOf: an opt-in check that a module's table is the one registered under each of its names, for TypeScript 5 programs whereskipLibCheckhides a collision.StateName: the registered state names. Dotted names andparent:both resolve; a future state'sname.**placeholder and a widenedstringname are left out.ParamsOfandResolvedParamsOf: the params a state accepts and the params it reads back, its ancestors' included. A param a state redeclares from an ancestor reads back as the nearest declaration types it; aboolpath param below a query declaration of the same key also readsundefined, since core decodes the absent query value over it. An untyped non-url redeclaration is core'sany: it takes whatever its ancestors take and reads back its own default, or else the value it took or an ancestor's url decoded, which is the nearest query declaration's when there is one, as core decodes query values after path ones. It readsunknownonly when no declaration above it constrains the key, and is optional to read when no declaration requires it. Core checks the value it takes against every declaration, so it takes only what each of them accepts. It is optional to pass when the nearest declaration's default passes that check, its own declaration's included, or when every declaration lets it go unset; an ancestor's default doesn't fill it. Url placeholders are required, query params and params with a default are optional to pass, and defaults are present to read. A default that is, or returns,nulladdsnullto a url or typed param; an untyped non-url param is core'sanyand reads as its default's type,unknownfornull.int,bool,dateandjsonplaceholders andtype:s map to TypeScript types; a param witharray: true, or aname[]id whose config leavesarrayunset, reads back as an array of that type, plus its scalarvaluedefault, which core reads back unwrapped aftertransitionTo; it takes one value or an array, since core wraps a scalar. A query param is in core's auto array mode unless its name ends in[]or its config setsarraytotrueorfalse: it takes one value or an array, and core reads two or more values back as an array.ResolvedParamsOftypes it as one value, which is an approximation; declaringarray: 'auto', which core accepts on query params only, types it as one value or an array, as core reads it back. An array path param whose type matches an empty segment reads backundefinedwhen the url leaves that segment empty, unless a default fills it in: untyped (:name,{name},*name), orstring,path,json,any,queryorhash, whether the placeholder or atype:names it. A regex placeholder or aParamTypeobject keeps its declared type, and a default that is, or returns,undefinedfills nothing in.TypedStateService: a view of core'sStateServicewhosego,transitionTo,target,href,is,includesandreloadtake registered names and their params. Relative refs are checked by their tail with loose params; object targets andUncheckedRefstay loose. It extendsStateService, so the two are assignable both ways: a typed getter needs no cast, and the view, or aUIRouterwhosestateServiceis typed with it, passes wherever core's type is expected.TypedRouteSnapshot: a view of the route snapshot the reactive packages share.includes(name)is a type predicate that narrowscurrentandparamsto that state's subtree.ui-router-registry/signals,/effectand/mobx: type-only entry points that fill theRouteTypesinterface ofui-router-signals,ui-router-effectandui-router-mobxfrom the registry, so their route snapshots areTypedRouteSnapshots.RegisteredRouteTypesholds the members they fill in.
Usage
Register each module's declarations next to its state table:
import type { StatesOf } from 'ui-router-registry';
export const contactsStates = [
{ name: 'contacts', url: '/contacts' },
{ name: 'contacts.contact', url: '/:contactId' },
] as const;
declare module 'ui-router-registry' {
interface RegisteredStates extends StatesOf<typeof contactsStates> {}
}Each module, lazy ones included, adds its own line, and every file sees every module's names. A class-declared state can sit in the table or be registered by hand: interface RegisteredStates { about: typeof AboutState }. Two modules that register one name with different rows are a TS2320 error in the registry's declarations; on TypeScript 5 skipLibCheck hides it and the first row wins, which AssertNoCollisions checks for.
Register takes every declaration at one site instead:
import type { appStates, lazyStates } from './states';
declare module 'ui-router-registry' {
interface Register {
states: (typeof appStates)[number] | (typeof lazyStates)[number];
}
}The registry reads both, so the two forms mix.
Then annotate where the router is used:
import type { TypedStateService } from 'ui-router-registry';
const stateService: TypedStateService = router.stateService;
stateService.go('contacts.contact', { contactId: 'c1' });Collisions across modules
When two modules register one name with different rows, the first row wins. TypeScript 7 reports TS2320 at each module's augmentation, and core throws State '…' is already defined when the second module registers. On TypeScript 5 the error lands in the registry's declarations, where skipLibCheck hides it. The check is opt-in: AssertNoCollisions takes a module's table and fails unless every row in it is the one registered under its name. Assert it next to the module's augmentation:
import type { AssertNoCollisions, StatesOf } from 'ui-router-registry';
declare module 'ui-router-registry' {
interface RegisteredStates extends StatesOf<typeof contactsStates> {}
}
export type ContactsStates = AssertNoCollisions<typeof contactsStates>;A row that collides fails at that line, as a missing 'not the row registered under' key holding the state's name. The assertion is a type, so it emits nothing; the export keeps noUnusedLocals quiet. A table that never augmented RegisteredStates collides on every name. CollisionsOf gives the colliding names as a union, never when there are none.
Reactive adapters
ui-router-signals, ui-router-effect and ui-router-mobx each declare an empty RouteTypes interface. A type-only import of the matching entry point, next to an augmentation, fills it in:
import type {} from 'ui-router-registry/signals';| Entry point | Fills in | Typed |
| ---------------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| ui-router-registry/signals | ui-router-signals' RouteTypes.snapshot | RouterSignals.route, and the selector of lit-ui-router-signals' RouterSignalController |
| ui-router-registry/effect | ui-router-effect's RouteTypes.snapshot | the value routeRef holds, and the selector of lit-ui-router-effect's RouterRefController; snapshotRoute stays untyped |
| ui-router-registry/mobx | ui-router-mobx's RouteTypes.snapshot and snapshots | RouterStore's current, params and includes, where includes(name) narrows the store |
The snapshot narrows as TypedRouteSnapshot does:
const route = RouterSignals.for(router).route.get();
if (route.includes('contacts.contact')) {
route.params.contactId; // string
}Until an app registers, the adapters keep their untyped RouteSnapshot, StateDeclaration and RawParams.
Relative refs and unchecked targets
A relative ref (.child, ^, ^.sibling, or . for the base state itself) resolves against the uiSref's context or options.relative, which types can't see. Its tail is checked against the registered names, so .contcat fails, and its params stay loose. A relative ref also lets a link reuse the current params instead of restating them: uiSref('.edit') from contacts.contact inherits contactId.
A target the registry can't see, such as a name built at runtime or a state registered at runtime, is a string and fails once an app registers. Opt out explicitly with UncheckedRef; its params are loose:
import type { UncheckedRef } from 'ui-router-registry';
uiSref(link.state as UncheckedRef, link.params);
stateService.go(name as UncheckedRef);Check components that call typed targets
A state declaration that names a component and is checked with satisfies against a type that inspects the component, such as LitStateDeclaration, makes that component part of the registered states' type. If one of the component's members calls a typed target (go, href, a typed uiSref wrapper) and has no declared return type, TypeScript has to infer that member from the registry while still building it, and reports a circular type (TS7022, TS7023, TS7024, TS2456, TS2502 or TS2313).
For lit-ui-router states, check the declarations with TypedLitStateDeclaration, which checks a LitElement class by its public members and a template function by its parameters, so it never infers render() or a template's body:
const contactState = {
name: 'contacts.contact',
url: '/:contactId',
component: ContactView,
} as const satisfies TypedLitStateDeclaration;Classes clear this way on every supported TypeScript, templates on TypeScript 5.5 and later. A component checked against a type that inspects it, or a template on TypeScript before 5.5, still needs a declared return type:
render(): TemplateResult {
return html`<a href=${this.stateService.href('contacts.contact', { contactId })}>…</a>`;
}A template written inline on the state declaration is inferred the same way, so declare its return type too:
{
name: 'account',
url: '/account',
component: (): TemplateResult => html`<a ${uiSref('contacts.contact', { contactId })}>…</a>`,
}Dependencies
@uirouter/core is a peer dependency, for its types only. ui-router-signals, ui-router-effect and ui-router-mobx are optional peers, each needed only by its entry point. Install one copy of this package per app: two copies mean two registries, and the augmentations type only one.
