Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to strictly type check route names #787

Merged
merged 1 commit into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
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
9 changes: 8 additions & 1 deletion src/js/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
*/
export interface RouteList {}

/**
* Marker interface to configure Ziggy's type checking behavior.
*/
export interface TypeConfig {}

/**
* A route name registered with Ziggy.
*/
Expand All @@ -13,7 +18,9 @@ type KnownRouteName = keyof RouteList;
/**
* A route name, or any string.
*/
type RouteName = KnownRouteName | (string & {});
type RouteName = TypeConfig extends { strictRouteNames: true }
? KnownRouteName
: KnownRouteName | (string & {});
// `(string & {})` prevents TypeScript from reducing this type to just `string`,
// which would prevent intellisense from autocompleting known route names.
// See https://stackoverflow.com/a/61048124/6484459.
Expand Down
7 changes: 7 additions & 0 deletions tests/js/route.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,10 @@ assertType(route().current('posts.comments.show', 'foo'));
assertType<string>(route('optional', { maybe: 'foo' }));
assertType<string>(route('optional', 'foo'));
assertType<Router>(route(undefined, undefined, undefined, {} as Config));

// Uncomment to test strict route name checking - invalid route names in this file should error
// declare module '../../src/js' {
// interface TypeConfig {
// strictRouteNames: true;
// }
// }