Skip to content

Commit fa1683d

Browse files
yangshuncpojer
andauthored
Preserve tuple types in typed fetch responses (#840)
Preserves tuples in typed fetch responses and correctly types JSON nulls and omitted object properties. Branded arrays retain their array methods, and readonly arrays remain readonly. Fixes #839. Verified a sample app against its actual generated `.void/routes.d.ts` with `strict` and `exactOptionalPropertyTypes`: ```ts const typedPairs: [number, number][] = pairs.pairs; // compiles without a response cast ``` - [Compiler regression coverage](https://github.com/voidzero-dev/void/blob/27a0fdf029ecb1d28d15bea88dba742fd6a0c5b9/packages/void/test/integration/route-response-types-typecheck.test.ts) checks exact inferred types and invalid usage. It reproduced the old `number[][]` assignment error before the fix. - Sample app: production build passed; 8/8 browser/API checks passed twice in both dev and production, with no console errors or failed requests. - Updated revision: full builds, workspace typechecks, formatting, lint, and 17,011 local tests passed. The compiler regressions cover Zod brands, readonly arrays, and additional array properties. All applicable GitHub CI checks pass on the updated revision, including both integration shards and npm/pnpm prepublish checks. --------- Co-authored-by: Christoph Nakazawa <cnakazawa@cloudflare.com>
1 parent 6bafd32 commit fa1683d

4 files changed

Lines changed: 240 additions & 36 deletions

File tree

‎docs/guide/type-safety.md‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -439,15 +439,20 @@ The dev server keeps route types up to date. After changing `routing.typedRoutes
439439

440440
## Serialization
441441

442-
The client types reflect JSON serialization through `Serialize<T>`:
443-
444-
| Source type | Serialized type |
445-
| --------------------------------- | ------------------------------------------------------ |
446-
| `string`, `number`, `boolean` | unchanged |
447-
| `Date` | `string` |
448-
| `Response` | excluded (passed through at runtime) |
449-
| `bigint`, `Function`, `undefined` | excluded |
450-
| `Array<T>` / `{ key: T }` | recursively serialized (function-valued keys stripped) |
442+
The typed fetch client reflects JSON serialization:
443+
444+
| Source type or value | Client type or behavior |
445+
| --------------------------------------------------- | --------------------------------------------------------------- |
446+
| `string`, `number`, `boolean`, `null` | unchanged |
447+
| `Date` | `string` |
448+
| Arrays and tuples, including readonly types | recursively serialized, preserving tuple shape and readonly |
449+
| `undefined`, functions, or symbols in an array | `null` |
450+
| `undefined`, functions, or symbols as object values | property omitted |
451+
| Symbol-keyed object properties | omitted |
452+
| `Response` | excluded from the inferred JSON type; passed through at runtime |
453+
| `bigint` | unsupported by JSON |
454+
455+
Object properties whose values may be omitted become optional in the client type. For example, a handler returning `{ label: string | undefined }` produces `{ label?: string }`.
451456

452457
## Context Variables
453458

‎packages/void/src/codegen/route-types.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,15 +88,35 @@ export function generateRouteTypes(
8888
lines.push(' >["output"];');
8989
lines.push('}');
9090
lines.push('');
91+
// JSON keeps invalid array positions as null, but omits the same values in objects.
92+
// Find optional object keys before Serialize removes their omitted-value union members.
93+
lines.push('type JsonOmitted = undefined | Function | symbol;');
94+
lines.push('type SerializeArrayElement<T> = T extends JsonOmitted ? null : Serialize<T>;');
95+
// A homomorphic map preserves ordinary arrays and tuples, but maps methods too
96+
// on array intersections (e.g. Zod brands). Rebuild those as JSON arrays.
97+
lines.push('type SerializeArray<T extends readonly unknown[]> =');
98+
lines.push(' { [K in keyof T]: SerializeArrayElement<T[K]> } extends infer A');
99+
lines.push(' ? A extends readonly unknown[] ? A');
100+
lines.push(' : T extends unknown[] ? Array<SerializeArrayElement<T[number]>>');
101+
lines.push(' : ReadonlyArray<SerializeArrayElement<T[number]>>');
102+
lines.push(' : never;');
103+
lines.push('type JsonOptionalKeys<T> = {');
104+
lines.push(' [K in keyof T]-?: Extract<T[K], JsonOmitted> extends never ? never : K;');
105+
lines.push('}[keyof T];');
106+
lines.push('type SerializeObject<T> = {');
107+
lines.push(
108+
' [K in keyof T as K extends symbol ? never : T[K] extends JsonOmitted ? never : K]: Serialize<T[K]>;',
109+
);
110+
lines.push('};');
111+
lines.push('');
91112
lines.push('type Serialize<T> =');
92113
lines.push(' T extends Response ? never :');
93114
lines.push(' T extends Date ? string :');
94115
lines.push(' T extends bigint ? never :');
95-
lines.push(' T extends Function ? never :');
96-
lines.push(' T extends undefined ? never :');
97-
lines.push(' T extends Array<infer U> ? Array<Serialize<U>> :');
116+
lines.push(' T extends JsonOmitted ? never :');
117+
lines.push(' T extends readonly unknown[] ? SerializeArray<T> :');
98118
lines.push(
99-
' T extends object ? { [K in keyof T as T[K] extends Function ? never : K]: Serialize<T[K]> } :',
119+
' T extends object ? SerializeObject<Omit<T, JsonOptionalKeys<T>> & Partial<Pick<T, JsonOptionalKeys<T>>>> :',
100120
);
101121
lines.push(' T;');
102122
lines.push('');
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
import { spawnSync } from 'node:child_process';
2+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3+
import { createRequire } from 'node:module';
4+
import { tmpdir } from 'node:os';
5+
import { dirname, join } from 'node:path';
6+
import { expect, it } from 'vite-plus/test';
7+
import { generateRouteTypes } from '../../src/codegen/route-types.ts';
8+
9+
it('preserves tuples and JSON omissions in generated typed fetch responses', () => {
10+
const root = mkdtempSync(join(tmpdir(), 'void-route-response-types-'));
11+
const voidDist = join(import.meta.dirname, '..', '..', 'dist');
12+
const { dts } = generateRouteTypes(
13+
{
14+
routes: [
15+
{
16+
pattern: '/api/serialization',
17+
methods: ['GET', 'POST'],
18+
params: [],
19+
catchAll: false,
20+
env: null,
21+
filePath: 'api/serialization.ts',
22+
},
23+
],
24+
middleware: [],
25+
jobs: [],
26+
queues: [],
27+
pages: { pages: [], layouts: [], namedLayouts: [] },
28+
},
29+
join(root, 'routes'),
30+
join(root, '.void'),
31+
);
32+
const files = {
33+
'package.json': JSON.stringify({ type: 'module' }),
34+
'tsconfig.json': JSON.stringify({
35+
compilerOptions: {
36+
target: 'ES2022',
37+
module: 'NodeNext',
38+
moduleResolution: 'NodeNext',
39+
lib: ['ES2022', 'DOM'],
40+
types: [],
41+
strict: true,
42+
exactOptionalPropertyTypes: true,
43+
noEmit: true,
44+
skipLibCheck: true,
45+
allowImportingTsExtensions: true,
46+
paths: {
47+
void: [join(voidDist, 'index.d.mts')],
48+
'void/client': [join(voidDist, 'runtime/client.d.mts')],
49+
'void/routes': [join(root, '.void/routes.d.ts')],
50+
zod: [
51+
join(
52+
dirname(createRequire(import.meta.url).resolve('zod/package.json')),
53+
'index.d.cts',
54+
),
55+
],
56+
},
57+
},
58+
files: ['.void/routes.d.ts', 'check.ts'],
59+
}),
60+
'.void/routes.d.ts': dts,
61+
'routes/api/serialization.ts': `
62+
import { defineHandler } from 'void';
63+
import { z } from 'zod';
64+
65+
const names = z.array(z.string()).brand<'Names'>().parse(['Alice']);
66+
const readonlyNames = z.array(z.string()).readonly().brand<'Names'>().parse(['Alice']);
67+
const datedPair = z.tuple([z.string(), z.date()]).brand<'DatedPair'>().parse(['Alice', new Date()]);
68+
69+
declare const hidden: unique symbol;
70+
declare const payload: {
71+
pairs: [number, number][];
72+
readonlyTuple: readonly [string, Date];
73+
empty: [];
74+
readonlyEmpty: readonly [];
75+
optionalTuple: [label: string, timestamp?: Date];
76+
restTuple: [number, ...Date[]];
77+
readonlyRestTuple: readonly [string, ...Date[]];
78+
invalidTuple: [number, undefined, () => void, symbol, string | undefined];
79+
invalidArray: Array<string | undefined | (() => void) | symbol>;
80+
dates: Date[];
81+
readonlyDates: readonly Date[];
82+
nested: Array<{ tuple: readonly [Date, { value: string | undefined }] }>;
83+
object: {
84+
readonly required: string;
85+
optional?: number;
86+
maybe: string | undefined;
87+
callback: () => void;
88+
optionalCallback?: () => void;
89+
mixed: string | (() => void);
90+
symbolValue: symbol;
91+
symbolUnion: number | symbol;
92+
omitted: undefined;
93+
[hidden]: number;
94+
nested: { value: Date | undefined; explicitNull: null };
95+
};
96+
union: { kind: 'a'; value: string | undefined } | { kind: 'b'; value: number };
97+
primitives: [string, number, boolean, null];
98+
neverArray: never[];
99+
};
100+
101+
export const GET = defineHandler(async () => ({
102+
...payload,
103+
names,
104+
readonlyNames,
105+
datedPair,
106+
decorated: Object.assign([new Date()], { total: 1 }),
107+
}));
108+
109+
declare const body: {
110+
readonly '~standard': {
111+
readonly version: 1;
112+
readonly vendor: string;
113+
readonly validate: (value: unknown) => { value: { name: string } };
114+
readonly types?: { readonly input: { name: string }; readonly output: { name: string } };
115+
};
116+
};
117+
export const POST = defineHandler.withValidator({ body })((_c, { body }) => ({
118+
greeting: body.name,
119+
pair: [body.name, new Date()] as [string, Date],
120+
}));
121+
`,
122+
'check.ts': `
123+
import { fetch } from 'void/client';
124+
125+
type Equal<X, Y> =
126+
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
127+
declare function assert<T extends true>(): void;
128+
129+
const result = await fetch('/api/serialization');
130+
assert<Equal<typeof result.pairs, [number, number][]>>();
131+
assert<Equal<typeof result.readonlyTuple, readonly [string, string]>>();
132+
assert<Equal<typeof result.empty, []>>();
133+
assert<Equal<typeof result.readonlyEmpty, readonly []>>();
134+
assert<Equal<typeof result.optionalTuple, [label: string, timestamp?: string | null]>>();
135+
assert<Equal<typeof result.restTuple, [number, ...string[]]>>();
136+
assert<Equal<typeof result.readonlyRestTuple, readonly [string, ...string[]]>>();
137+
assert<Equal<typeof result.invalidTuple, [number, null, null, null, string | null]>>();
138+
assert<Equal<typeof result.invalidArray, Array<string | null>>>();
139+
assert<Equal<typeof result.dates, string[]>>();
140+
assert<Equal<typeof result.readonlyDates, readonly string[]>>();
141+
assert<Equal<typeof result.nested, Array<{ tuple: readonly [string, { value?: string }] }>>>();
142+
assert<Equal<typeof result.object, {
143+
readonly required: string;
144+
optional?: number;
145+
maybe?: string;
146+
mixed?: string;
147+
symbolUnion?: number;
148+
nested: { value?: string; explicitNull: null };
149+
}>>();
150+
assert<Equal<typeof result.union, { kind: 'a'; value?: string } | { kind: 'b'; value: number }>>();
151+
assert<Equal<typeof result.primitives, [string, number, boolean, null]>>();
152+
assert<Equal<typeof result.neverArray, never[]>>();
153+
assert<Equal<typeof result.names, string[]>>();
154+
assert<Equal<typeof result.readonlyNames, readonly string[]>>();
155+
assert<Equal<typeof result.datedPair, string[]>>();
156+
assert<Equal<typeof result.decorated, string[]>>();
157+
const names: string[] = result.names.map((name) => name.toUpperCase());
158+
const dates: string[] = result.decorated.map((date) => date.toUpperCase());
159+
// @ts-expect-error readonly arrays retain readonly methods
160+
result.readonlyNames.push('Bob');
161+
// @ts-expect-error JSON omits additional array properties
162+
result.decorated.total;
163+
164+
const pairs: [number, number][] = result.pairs;
165+
// @ts-expect-error tuples retain their length
166+
pairs[0][2];
167+
// @ts-expect-error serialized Dates are strings
168+
result.dates[0].getTime();
169+
// @ts-expect-error function properties are omitted
170+
result.object.callback;
171+
// @ts-expect-error properties that can be omitted require a check
172+
result.object.maybe.toUpperCase();
173+
174+
const posted = await fetch('/api/serialization', { method: 'POST', body: { name: 'Alice' } });
175+
assert<Equal<typeof posted, { greeting: string; pair: [string, string] }>>();
176+
// @ts-expect-error validators still constrain request bodies
177+
await fetch('/api/serialization', { method: 'POST', body: { name: 42 } });
178+
`,
179+
};
180+
181+
try {
182+
for (const [path, content] of Object.entries(files)) {
183+
mkdirSync(dirname(join(root, path)), { recursive: true });
184+
writeFileSync(join(root, path), content);
185+
}
186+
const tsc = join(
187+
dirname(createRequire(import.meta.url).resolve('typescript/package.json')),
188+
'bin/tsc',
189+
);
190+
const result = spawnSync(process.execPath, [tsc, '-p', join(root, 'tsconfig.json')], {
191+
encoding: 'utf8',
192+
timeout: 30_000,
193+
});
194+
expect(result.error).toBeUndefined();
195+
expect(result.status, result.stdout + result.stderr).toBe(0);
196+
} finally {
197+
rmSync(root, { recursive: true, force: true });
198+
}
199+
});

‎packages/void/test/unit/route-type-extraction.typecheck.ts‎

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,6 @@ import { z } from 'zod';
55
import { defineHandler, defineMiddleware } from '../../src/runtime/handler.ts';
66
import type { StandardSchemaV1 } from '../../src/standard-schema.ts';
77

8-
/**
9-
* Copies of the helpers generateRouteTypes() emits into .void/routes.d.ts, applied to
10-
* `typeof handler` in place of `typeof import("../routes/...")["METHOD"]`.
11-
*/
12-
type Serialize<T> = T extends Response
13-
? never
14-
: T extends Date
15-
? string
16-
: T extends bigint
17-
? never
18-
: T extends Function
19-
? never
20-
: T extends undefined
21-
? never
22-
: T extends Array<infer U>
23-
? Array<Serialize<U>>
24-
: T extends object
25-
? { [K in keyof T as T[K] extends Function ? never : K]: Serialize<T[K]> }
26-
: T;
27-
288
type ExtractInput<V> = {
299
[K in keyof V as V[K] extends StandardSchemaV1 ? K : never]: V[K] extends StandardSchemaV1
3010
? StandardSchemaV1.InferInput<V[K]>
@@ -33,12 +13,12 @@ type ExtractInput<V> = {
3313

3414
// ─── Output extraction ──────────────────────────────────────────────────────
3515

36-
describe('Serialize<Awaited<handler.__output>>', () => {
16+
describe('Awaited<handler.__output>', () => {
3717
it('extracts plain object return type', () => {
3818
const handler = defineHandler((_c) => {
3919
return { name: 'Alice' as string, age: 30 as number };
4020
});
41-
type Output = Serialize<Awaited<(typeof handler)['__output']>>;
21+
type Output = Awaited<(typeof handler)['__output']>;
4222

4323
expectTypeOf<Output>().toEqualTypeOf<{ name: string; age: number }>();
4424

@@ -52,7 +32,7 @@ describe('Serialize<Awaited<handler.__output>>', () => {
5232
})((_c, { body }) => {
5333
return { greeting: `Hello ${body.name}` as string };
5434
});
55-
type Output = Serialize<Awaited<(typeof handler)['__output']>>;
35+
type Output = Awaited<(typeof handler)['__output']>;
5636

5737
expectTypeOf<Output>().toEqualTypeOf<{ greeting: string }>();
5838
});

0 commit comments

Comments
 (0)