From 36cdd32b760424ac5775ba086b3fe5258c46f2f8 Mon Sep 17 00:00:00 2001 From: Jacob Baker-Kretzmar Date: Fri, 22 Dec 2023 15:36:24 -0500 Subject: [PATCH] Refactor type mapping --- src/js/index.d.ts | 30 ++++++++++++------------------ tests/js/route.test-d.ts | 4 +--- 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/src/js/index.d.ts b/src/js/index.d.ts index 78e2420a..b45ea5f6 100644 --- a/src/js/index.d.ts +++ b/src/js/index.d.ts @@ -21,7 +21,7 @@ type RouteName = KnownRouteName | (string & {}); /** * Information about a single route parameter. */ -type ParameterInfo = { name: string; binding?: string }; +type ParameterInfo = { name: string; optional: boolean; binding?: string }; /** * A primitive route parameter value, as it would appear in a URL. @@ -62,30 +62,24 @@ type HasQueryParam = { _query?: Record }; type GenericRouteParamsObject = Record & HasQueryParam; // `keyof any` essentially makes it function as a plain `Record` -/** - * Get only params for `optional: true` or `optional: false`. - */ -type GetParamsForOptionalSwitch = Extract< - I[number], - { optional: TOptional } ->; - -/** - * Map our parameter info to a routable object. We call twice to handle optional and non-optional params. - */ -type MapParamsToRoutable = - { [T in GetParamsForOptionalSwitch as T['name']]?: Routable } & - { [T in GetParamsForOptionalSwitch as T['name']]: Routable } - /** * An object of parameters for a specific named route. */ -type KnownRouteParamsObject> = { - [K in keyof MappedParams]: MappedParams[K] +type KnownRouteParamsObject = { + [T in Extract as T['name']]: Routable; +} & { + [T in Extract as T['name']]?: Routable; } & GenericRouteParamsObject; // `readonly` allows TypeScript to determine the actual values of all the // parameter names inside the array, instead of just seeing `string`. // See https://github.com/tighten/ziggy/pull/664#discussion_r1329978447. + +// Uncomment to test: +// type A = KnownRouteParamsObject< +// [{ name: 'foo'; optional: false }, { name: 'bar'; optional: true }] +// >; +// = { foo: ..., bar?: ... } + /** * An object of route parameters. */ diff --git a/tests/js/route.test-d.ts b/tests/js/route.test-d.ts index 425d169c..b8b55d56 100644 --- a/tests/js/route.test-d.ts +++ b/tests/js/route.test-d.ts @@ -1,5 +1,5 @@ import { assertType } from 'vitest'; -import route, { RouteParams } from '../../src/js'; +import route from '../../src/js'; // Add generated routes to use for testing inside this file. In a real app these declarations // would be in a separate file generated by running `php artisan ziggy:generate --types`. @@ -15,8 +15,6 @@ declare module '../../src/js' { } } -type T = RouteParams<'posts.comments.show'>; - // Test route name autocompletion by adding quotes inside `route()` - should suggest route names above assertType(route());