Skip to content

Commit c7e05d8

Browse files
authored
fix(core): optional url parameters typing without path params (#517)
1 parent ec6bc01 commit c7e05d8

3 files changed

Lines changed: 26 additions & 4 deletions

File tree

.changeset/three-pillows-tan.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@ts-rest/core': patch
3+
---
4+
5+
Fix optional path parameters showing in types with a question mark if path params are not used

libs/ts-rest/core/src/lib/paths.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ expectType<{ id: string; commentId: string; commentId2: string }>(
2222
type<ParamsFromUrl<typeof urlManyParams>>(),
2323
);
2424

25+
const urlOptional = '/post/:id?';
26+
expectType<{
27+
id: string;
28+
}>(type<ParamsFromUrl<typeof urlOptional>>());
29+
30+
const urlManyOptional = '/post/:id?/comments/:commentId?';
31+
expectType<{
32+
id: string;
33+
commentId: string;
34+
}>(type<ParamsFromUrl<typeof urlManyOptional>>());
35+
2536
describe('insertParamsIntoPath', () => {
2637
it('should insert params into path', () => {
2738
const path = '/post/:id/comments/:commentId';

libs/ts-rest/core/src/lib/paths.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
type StripOptional<T> = T extends `${infer U}?` ? U : T;
2+
13
/**
24
* @params T - The URL e.g. /posts/:id
35
* @params TAcc - Accumulator object
@@ -6,17 +8,21 @@ type RecursivelyExtractPathParams<
68
T extends string,
79
TAcc extends null | Record<string, string>,
810
> = T extends `/:${infer PathParam}/${infer Right}`
9-
? { [key in PathParam]: string } & RecursivelyExtractPathParams<Right, TAcc>
11+
? {
12+
[key in StripOptional<PathParam>]: string;
13+
} & RecursivelyExtractPathParams<Right, TAcc>
1014
: T extends `/:${infer PathParam}`
11-
? { [key in PathParam]: string }
15+
? { [key in StripOptional<PathParam>]: string }
1216
: T extends `/${string}/${infer Right}`
1317
? RecursivelyExtractPathParams<Right, TAcc>
1418
: T extends `/${string}`
1519
? TAcc
1620
: T extends `:${infer PathParam}/${infer Right}`
17-
? { [key in PathParam]: string } & RecursivelyExtractPathParams<Right, TAcc>
21+
? {
22+
[key in StripOptional<PathParam>]: string;
23+
} & RecursivelyExtractPathParams<Right, TAcc>
1824
: T extends `:${infer PathParam}`
19-
? TAcc & { [key in PathParam]: string }
25+
? TAcc & { [key in StripOptional<PathParam>]: string }
2026
: T extends `${string}/${infer Right}`
2127
? RecursivelyExtractPathParams<Right, TAcc>
2228
: TAcc;

0 commit comments

Comments
 (0)