@evobug_com/safe-ts-skill 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1074 @@
1
+ # Pattern catalogue: TypeScript (any framework)
2
+
3
+ One entry per idiom a migration meets, with the code before and after. Vue components are in
4
+ [patterns-vue.md](patterns-vue.md), React components in [patterns-react.md](patterns-react.md).
5
+
6
+ How to read the blocks:
7
+
8
+ - ` ```ts bad <rules> ` is the code before. The words after `bad` are the rules `safe-ts check`
9
+ reports on it, with the idiomatic layer (`"idiomatic": true`) and the feature packs on. Many
10
+ of them are idiomatic rules, which report as warnings: `safe-ts check` exits 0 on warnings
11
+ alone, so run it with `--deny-warnings` (see [order-and-gates.md](order-and-gates.md#gates-per-step)).
12
+ **`bad` with no rules means the checker is silent**: these are the patterns a checker-driven
13
+ migration leaves behind, and the census finds them instead.
14
+ - ` ```ts good ` is the target. The checker accepts it, and tsc compiles it in strict mode
15
+ with `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes`.
16
+
17
+ Both kinds are tested in the SAFE-TS repository against the version this skill was written for.
18
+ The guide pages linked from each entry say more; read them when an entry doesn't fit.
19
+
20
+ ## Contents
21
+
22
+ - [A function that throws](#a-function-that-throws)
23
+ - [Passing an error up](#passing-an-error-up)
24
+ - [Requests return a Result](#requests-return-a-result)
25
+ - [Try and catch around your own code](#try-and-catch-around-your-own-code)
26
+ - [A failure turned into undefined](#a-failure-turned-into-undefined)
27
+ - [A sentinel value](#a-sentinel-value)
28
+ - [A closed set of states](#a-closed-set-of-states)
29
+ - [A set of boolean flags](#a-set-of-boolean-flags)
30
+ - [Reading an enum: one style](#reading-an-enum-one-style)
31
+ - [A union told apart by keys](#a-union-told-apart-by-keys)
32
+ - [An API that sends null](#an-api-that-sends-null)
33
+ - [JSON and storage](#json-and-storage)
34
+ - [A cast](#a-cast)
35
+ - [A hand-written type guard](#a-hand-written-type-guard)
36
+ - [An index read](#an-index-read)
37
+ - [An optional key](#an-optional-key)
38
+ - [A table keyed by server data](#a-table-keyed-by-server-data)
39
+ - [A server value from a list that can grow](#a-server-value-from-a-list-that-can-grow)
40
+ - [Base64](#base64)
41
+ - [A trusted boundary](#a-trusted-boundary)
42
+ - [Strict code with legacy callers that pass null](#strict-code-with-legacy-callers-that-pass-null)
43
+ - [Command-line arguments](#command-line-arguments)
44
+ - [IndexedDB](#indexeddb)
45
+ - [A bug inside a Result-returning call](#a-bug-inside-a-result-returning-call)
46
+ - [panic on a loading state](#panic-on-a-loading-state)
47
+ - [Casts in tests](#casts-in-tests)
48
+
49
+ ## A function that throws
50
+
51
+ A caller can't see that `findName` throws, so it doesn't handle it. Return the error.
52
+ `safe-ts migrate throw-to-result <dir>` does this for the functions it can convert safely
53
+ (guide: Adopting SAFE-TS, "Migrating with codemods").
54
+
55
+ ```ts bad no-throw
56
+ export class NotFound extends Error {}
57
+
58
+ const names = new Map([["1", "Ada"]]);
59
+
60
+ export function findName(id: string): string {
61
+ const name = names.get(id);
62
+ if (name === undefined) throw new NotFound(`no user ${id}`);
63
+ return name;
64
+ }
65
+ ```
66
+
67
+ ```ts good
68
+ import { err, type Result } from "@evobug_com/safe-ts-std/result";
69
+
70
+ export class NotFound extends Error {}
71
+
72
+ const names = new Map([["1", "Ada"]]);
73
+
74
+ export function findName(id: string): Result<string, NotFound> {
75
+ const name = names.get(id);
76
+ if (name === undefined) return err(new NotFound(`no user ${id}`));
77
+ return name;
78
+ }
79
+ ```
80
+
81
+ When a failure should end a whole request, job or command (not be handled by the next
82
+ caller), throw a subclass of `PropagateError` and catch it in one place at the top (guide:
83
+ Errors, "When the whole request should stop"). `throw new Error(...)` is never the answer.
84
+
85
+ ## Passing an error up
86
+
87
+ `if (isErr(x)) return x` after every call is correct and long. `q(...)` says it in one line,
88
+ and the build turns it into that `if`. When the error type changes on the way up, give `q` the
89
+ mapping, or use `mapErr` outside `q` (guide: Errors, "Pass an error up with q(...)"). With the
90
+ idiomatic layer on, `prefer-q` reports the `if (isErr(x)) return x` (its quick fix writes the
91
+ `q`), and `prefer-map-err` the error re-wrapped by hand.
92
+
93
+ ```ts bad prefer-map-err prefer-q
94
+ import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
95
+
96
+ type Upload = { readonly size: number };
97
+ type UploadError = { readonly kind: "invalid"; readonly detail: string };
98
+
99
+ declare function checkUpload(size: number): Result<Upload, string>;
100
+ declare function storeUpload(upload: Upload): Result<string, UploadError>;
101
+
102
+ export function startUpload(size: number): Result<string, UploadError> {
103
+ const upload = checkUpload(size);
104
+ if (isErr(upload)) return err({ kind: "invalid", detail: upload.error });
105
+ const id = storeUpload(upload);
106
+ if (isErr(id)) return id;
107
+ return id;
108
+ }
109
+ ```
110
+
111
+ ```ts good
112
+ import { q, type Result } from "@evobug_com/safe-ts-std/result";
113
+
114
+ type Upload = { readonly size: number };
115
+ type UploadError = { readonly kind: "invalid"; readonly detail: string };
116
+
117
+ declare function checkUpload(size: number): Result<Upload, string>;
118
+ declare function storeUpload(upload: Upload): Result<string, UploadError>;
119
+
120
+ const invalid = (detail: string): UploadError => ({ kind: "invalid", detail });
121
+
122
+ export function startUpload(size: number): Result<string, UploadError> {
123
+ const upload = q(checkUpload(size), invalid);
124
+ const id = q(storeUpload(upload));
125
+ return id;
126
+ }
127
+ ```
128
+
129
+ `q(...)` is a statement of its own (`const x = q(...)`, `x = q(...)`, `q(...);`,
130
+ `return q(...)`), in a function that returns a `Result`. It needs the build transform: the
131
+ Vite plugin, or `node --import @evobug_com/safe-ts-transform/register` for code Node runs.
132
+
133
+ ## Requests return a Result
134
+
135
+ A raw `fetch` can wait forever, rejects on a network failure, and `response.json()` gives
136
+ `any`. A request function owns all three: a time limit and the caller's signal, the failure as
137
+ a typed error, and the body checked against the type.
138
+
139
+ ```ts bad fetch-signal unhandled-failure
140
+ export type User = { readonly id: number; readonly name: string };
141
+
142
+ export async function fetchUser(id: number): Promise<User> {
143
+ const response = await fetch(`/api/users/${id}`);
144
+ const user: User = await response.json();
145
+ return user;
146
+ }
147
+ ```
148
+
149
+ ```ts good
150
+ import { fetch, json } from "@evobug_com/safe-ts-feature-browser/fetch";
151
+ import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
152
+ import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
153
+ import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
154
+
155
+ export type User = { readonly id: number; readonly name: string };
156
+
157
+ export type RequestError = Enum<{
158
+ Network: { reason: string };
159
+ Status: { status: number };
160
+ Body: { problem: JsonError };
161
+ }>;
162
+ export const RequestError = constructors<RequestError>();
163
+
164
+ const network = (cause: unknown): RequestError => RequestError.Network({ reason: String(cause) });
165
+ const body = (problem: JsonError): RequestError => RequestError.Body({ problem });
166
+
167
+ export async function fetchUser(id: number, signal: AbortSignal): Promise<Result<User, RequestError>> {
168
+ const limit = AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
169
+ const response = q(await fetch(`/api/users/${id}`, { signal: limit }), network);
170
+ if (!response.ok) return err(RequestError.Status({ status: response.status }));
171
+ const data: unknown = q(await json(response), network);
172
+ return q(validate<User>(data), body);
173
+ }
174
+ ```
175
+
176
+ - Every request function takes a `signal` (a component's `useTask` passes its own), and adds a
177
+ time limit made per request.
178
+ - The error is an `Enum`, so callers `match` on it: a 422's message shown inline is a
179
+ different variant from a dropped connection, and nothing is lost on the way to the screen.
180
+ - The same shape works around an HTTP client (axios, ky): `unsafeAsync(() => client.get(...))`
181
+ for the rejection, then `validate<T>` on the data. Put one such function per endpoint, or
182
+ one generic `request<T>` whose callers always give `T` (a `Result<unknown, E>` is just
183
+ `unknown`, and `no-unknown-in-result` reports it).
184
+ - With the browser pack enabled, the pack's `fetch` is the safe version of the global, and
185
+ `json(response)` of `response.json()` (guide: Libraries and feature packs).
186
+ - `fetch-signal` reports a bare `fetch(...)` without a `signal`. List the project's own request
187
+ wrapper or axios instance in package.json, `"safe-ts": { "requestFunctions": ["api"] }`, and
188
+ a call of it (or of a method on it, `api.get(url)`) without a `signal` or `timeout` is
189
+ reported too.
190
+ - With the idiomatic layer on, `misplaced-axios-check` reports an `isAxiosError(r.error)` on a
191
+ function that has its own error type: match on that type's variants instead.
192
+
193
+ ## Try and catch around your own code
194
+
195
+ A `try` around code of your own hides which call failed and what kind of failure it was. Once
196
+ the functions it calls return `Result`s, the `try` has nothing left to catch, and a `.catch` on a
197
+ `Promise<Result<...>>` catches nothing either (it only looks like handling). Remove both when
198
+ the callee changes, at every caller. The checker helps: `must-use-result` follows a `Result`
199
+ through store members (Pinia setup and options stores), returned objects and factories, and
200
+ reports one that is dropped, `.catch(() => {})` included; with the idiomatic layer on,
201
+ `catch-on-result` reports a `.catch` or a `try` around nothing but calls that return a `Result`.
202
+ It can't see a function reached through a parameter, a class field, a `ref` or a `Map` (rule
203
+ page `must-use-result`, "What the rule can't see"): search for each changed function's name
204
+ too.
205
+
206
+ ```ts bad
207
+ declare function saveDraft(text: string): Promise<void>;
208
+
209
+ export async function onSave(text: string, show: (message: string) => void): Promise<void> {
210
+ try {
211
+ await saveDraft(text);
212
+ show("Saved");
213
+ } catch {
214
+ show("Could not save");
215
+ }
216
+ }
217
+ ```
218
+
219
+ ```ts good
220
+ import { isErr, type Result } from "@evobug_com/safe-ts-std/result";
221
+
222
+ type SaveError = { readonly message: string };
223
+
224
+ declare function saveDraft(text: string): Promise<Result<void, SaveError>>;
225
+
226
+ export async function onSave(text: string, show: (message: string) => void): Promise<void> {
227
+ const saved = await saveDraft(text);
228
+ show(isErr(saved) ? `Could not save: ${saved.error.message}` : "Saved");
229
+ }
230
+ ```
231
+
232
+ The `try` left behind once `saveDraft` returns a `Result`:
233
+
234
+ ```ts bad catch-on-result
235
+ import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
236
+
237
+ type SaveError = { readonly message: string };
238
+
239
+ async function saveDraft(text: string): Promise<Result<void, SaveError>> {
240
+ return text === "" ? err({ message: "nothing to save" }) : undefined;
241
+ }
242
+
243
+ export async function onSave(text: string): Promise<string> {
244
+ let saved: Result<void, SaveError>;
245
+ try {
246
+ saved = await saveDraft(text);
247
+ } catch {
248
+ return "Could not save";
249
+ }
250
+ return isErr(saved) ? `Could not save: ${saved.error.message}` : "Saved";
251
+ }
252
+ ```
253
+
254
+ A `try` stays where code of someone else's throws and no safe version exists (wrap it in
255
+ `unsafe(...)` with a reason instead, see [escape-hatches.md](escape-hatches.md)), and at a
256
+ harness boundary that runs independent units of work and reports each failure (guide: Errors,
257
+ "When catching everything is right: harness boundaries").
258
+
259
+ ## A failure turned into undefined
260
+
261
+ `unwrapOr(result, undefined)`, `.catch(() => undefined)` and `if (isErr(r)) return undefined`
262
+ make a corrupt value look like a missing one. Return the `Result`, with `Option` inside it when
263
+ "missing" is a real answer. `no-swallowed-error` (idiomatic) reports each of these, `.catch(()
264
+ => {})`, `.catch(() => null)` and `unwrapOr(result, null)` too, and every call of a one-line
265
+ helper that does one of them (an `orNone(parseJson(text))`): don't write one.
266
+
267
+ ```ts bad no-swallowed-error
268
+ import { parseJson } from "@evobug_com/safe-ts-std/json";
269
+ import { isErr, type Option } from "@evobug_com/safe-ts-std/result";
270
+
271
+ type Save = { readonly level: number };
272
+
273
+ export function savedLevel(text: string): Option<number> {
274
+ const save = parseJson<Save>(text);
275
+ if (isErr(save)) return undefined;
276
+ return save.level;
277
+ }
278
+ ```
279
+
280
+ ```ts good
281
+ import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
282
+ import { q } from "@evobug_com/safe-ts-std/result";
283
+
284
+ type Save = { readonly level: number };
285
+
286
+ export function savedLevel(text: string): JsonResult<number> {
287
+ const save = q(parseJson<Save>(text));
288
+ return save.level;
289
+ }
290
+ ```
291
+
292
+ Where a failure really does mean "missing" for this caller, report it first (log it, show it),
293
+ then return `undefined`: the rule accepts a branch that does something with the error.
294
+
295
+ ## A sentinel value
296
+
297
+ `''` for "no error", `-1` for "not found" and `0` for "nothing selected" are values of the
298
+ type, so nothing makes the caller test for them. Say what the function returns: `Option<T>`
299
+ for "maybe missing", `Result<void, E>` for a command that can fail, an `Enum` variant when
300
+ "none" carries meaning of its own. With the idiomatic layer on, `sentinel-error` reports the
301
+ `''`-for-no-error case, and `strict-truthiness` the `if (block)` that reads it: a test of a
302
+ string or number for truth hides `""` and `0` along with `undefined`. Compare with what is
303
+ meant (`!== undefined`, `> 0`).
304
+
305
+ ```ts bad sentinel-error strict-truthiness
306
+ type Wallet = { readonly balance: number };
307
+
308
+ export function buyBlock(wallet: Wallet, price: number): string {
309
+ return price > wallet.balance ? `costs ${price} EUR` : "";
310
+ }
311
+
312
+ export function buyTitle(wallet: Wallet, price: number): string {
313
+ const block = buyBlock(wallet, price);
314
+ return block ? `Can't buy: ${block}` : "Buy";
315
+ }
316
+ ```
317
+
318
+ ```ts good
319
+ import type { Option } from "@evobug_com/safe-ts-std/result";
320
+
321
+ type Wallet = { readonly balance: number };
322
+
323
+ export function buyBlock(wallet: Wallet, price: number): Option<string> {
324
+ return price > wallet.balance ? `costs ${price} EUR` : undefined;
325
+ }
326
+
327
+ export function buyTitle(wallet: Wallet, price: number): string {
328
+ const block = buyBlock(wallet, price);
329
+ return block === undefined ? "Buy" : `Can't buy: ${block}`;
330
+ }
331
+ ```
332
+
333
+ The `-1` of `indexOf` is the same trap, and the checker is silent on it:
334
+
335
+ ```ts bad
336
+ const SIZES = ["small", "medium", "large"] as const;
337
+
338
+ export function sizeRank(input: string): number {
339
+ return SIZES.findIndex((size) => size === input);
340
+ }
341
+
342
+ export function isKnownSize(input: string): boolean {
343
+ return sizeRank(input) !== -1;
344
+ }
345
+ ```
346
+
347
+ ```ts good
348
+ import { indexIn } from "@evobug_com/safe-ts-std/array";
349
+ import type { Option } from "@evobug_com/safe-ts-std/result";
350
+
351
+ const SIZES = ["small", "medium", "large"] as const;
352
+
353
+ export function sizeRank(input: string): Option<0 | 1 | 2> {
354
+ return indexIn(SIZES, input);
355
+ }
356
+
357
+ export function isKnownSize(input: string): boolean {
358
+ return sizeRank(input) !== undefined;
359
+ }
360
+ ```
361
+
362
+ A sentinel inside a project helper's contract (a callback that returns `''` to mean "use the
363
+ default") is the same thing: change the contract to `Option<string>`, and drop the sentence
364
+ that describes the `''` from the project's conventions.
365
+
366
+ ## A closed set of states
367
+
368
+ A value that is one of a few kinds, handled with `if`/`else if` on strings, compiles when a
369
+ kind is added and every chain misses it. An `Enum` with `match` stops compiling instead. Each
370
+ variant carries only its own data. For a union already discriminated by a `type` field,
371
+ `safe-ts migrate union-to-enum <Type> <dir>` converts it with its producers and consumers.
372
+
373
+ ```ts bad
374
+ export type Payment = {
375
+ readonly kind: "card" | "transfer" | "cash";
376
+ readonly last4?: string;
377
+ readonly iban?: string;
378
+ };
379
+
380
+ export function paymentLabel(payment: Payment): string {
381
+ if (payment.kind === "card") return `Card ending ${payment.last4 ?? "????"}`;
382
+ if (payment.kind === "transfer") return `Transfer from ${payment.iban ?? "unknown"}`;
383
+ return "Cash";
384
+ }
385
+ ```
386
+
387
+ ```ts good
388
+ import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
389
+
390
+ export type Payment = Enum<{
391
+ Card: { last4: string };
392
+ Transfer: { iban: string };
393
+ Cash: {};
394
+ }>;
395
+ export const Payment = constructors<Payment>();
396
+
397
+ export function paymentLabel(payment: Payment): string {
398
+ return match(payment, {
399
+ Card: ({ last4 }) => `Card ending ${last4}`,
400
+ Transfer: ({ iban }) => `Transfer from ${iban}`,
401
+ Cash: () => "Cash",
402
+ });
403
+ }
404
+ ```
405
+
406
+ Plain names with no data (`"asc" | "desc"`) can stay a union of strings; the `Enum` pays off
407
+ when the kinds carry different data or when every kind needs its own decision.
408
+
409
+ ## A set of boolean flags
410
+
411
+ `isOpen`, `isSaving` and `hasFailed` side by side allow combinations that make no sense (saving
412
+ and failed at once) and need every reader to know which wins. When at most one can be true,
413
+ they are one value.
414
+
415
+ ```ts bad
416
+ export type Dialog = {
417
+ readonly isOpen: boolean;
418
+ readonly isSaving: boolean;
419
+ readonly failure: string;
420
+ };
421
+
422
+ export function dialogTitle(dialog: Dialog): string {
423
+ if (!dialog.isOpen) return "";
424
+ if (dialog.isSaving) return "Saving…";
425
+ return dialog.failure === "" ? "Edit" : `Failed: ${dialog.failure}`;
426
+ }
427
+ ```
428
+
429
+ ```ts good
430
+ import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
431
+
432
+ export type Dialog = Enum<{
433
+ Closed: {};
434
+ Editing: {};
435
+ Saving: {};
436
+ Failed: { reason: string };
437
+ }>;
438
+ export const Dialog = constructors<Dialog>();
439
+
440
+ export function dialogTitle(dialog: Dialog): string {
441
+ return match(dialog, {
442
+ Closed: () => "",
443
+ Editing: () => "Edit",
444
+ Saving: () => "Saving…",
445
+ Failed: ({ reason }) => `Failed: ${reason}`,
446
+ });
447
+ }
448
+ ```
449
+
450
+ When the flags describe async work (loading, failed, loaded), the value is `AsyncState`, kept
451
+ by `useTask`: see the trio entry of the framework catalogue.
452
+
453
+ ## Reading an enum: one style
454
+
455
+ Both `x.tag === "Ready"` and `is(x, ...)` / `variant(...)` / `match` compile and narrow. The
456
+ SAFE-TS style is the second, and with the idiomatic layer on, `prefer-is-over-tag` reports the
457
+ raw tag (`x.tag === "..."`, `x.tag !== "..."`, `switch (x.tag)`) in code and in Vue templates,
458
+ with a quick fix to `is(x, "Ready")`. Write the style in the project's conventions:
459
+
460
+ - `match(value, { ... })` when every variant needs its own decision: a variant added later
461
+ makes it stop compiling.
462
+ - `is(value, Type.Variant)` for "is it this one?", `variant(value, Type.Variant)?.field` to
463
+ read one variant's data, and `_` in `match` for "everything else". Generic enums take the
464
+ constructor too: `is(state, AsyncState.Ready)`, `variant(state, AsyncState.Ready)?.value`.
465
+ - In Vue templates, `<Match :value="state">` with a slot per variant (vue-tsc accepts it; the
466
+ older `:on` fails vue-tsc), or a `v-if` chain of `is(state, AsyncState.Ready)`, which
467
+ `vue-exhaustive-v-if` checks like one on `.tag`; in JSX, `<Match on={state} ... />`.
468
+
469
+ ```ts bad prefer-is-over-tag
470
+ import type { Enum } from "@evobug_com/safe-ts-std/enum";
471
+
472
+ type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
473
+
474
+ export function publishedAt(status: Status): string {
475
+ return status.tag === "Published" ? status.at : "not published";
476
+ }
477
+ ```
478
+
479
+ ```ts good
480
+ import { constructors, type Enum, variant } from "@evobug_com/safe-ts-std/enum";
481
+
482
+ type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
483
+ const Status = constructors<Status>();
484
+
485
+ export function publishedAt(status: Status): string {
486
+ return variant(status, Status.Published)?.at ?? "not published";
487
+ }
488
+ ```
489
+
490
+ The build turns `is` and `variant` on a plain variable into the same tag check, so the style
491
+ costs nothing at runtime (guide: Enums and match).
492
+
493
+ ## A union told apart by keys
494
+
495
+ `'issueId' in choice` narrows in TypeScript, but the union has no name for its kinds and any
496
+ object with that key fits. Give each kind a tag. With the idiomatic layer on,
497
+ `key-presence-union` reports `"key" in x` that tells apart the members of a union declared in
498
+ the project.
499
+
500
+ ```ts bad key-presence-union
501
+ type ByIssue = { readonly issueId: number };
502
+ type ByBranch = { readonly branch: string };
503
+ export type Target = ByIssue | ByBranch;
504
+
505
+ export function targetLabel(target: Target): string {
506
+ return "issueId" in target ? `#${target.issueId}` : target.branch;
507
+ }
508
+ ```
509
+
510
+ ```ts good
511
+ import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
512
+
513
+ export type Target = Enum<{ Issue: { issueId: number }; Branch: { branch: string } }>;
514
+ export const Target = constructors<Target>();
515
+
516
+ export function targetLabel(target: Target): string {
517
+ return match(target, {
518
+ Issue: ({ issueId }) => `#${issueId}`,
519
+ Branch: ({ branch }) => branch,
520
+ });
521
+ }
522
+ ```
523
+
524
+ Keep `in` for objects from outside whose shape you are finding out (and prefer `validate<T>`
525
+ for those).
526
+
527
+ ## An API that sends null
528
+
529
+ The server sends `null` for "none". Convert it where the data comes in, so the rest of the
530
+ code sees `undefined`: `validate<T>` and `parseJson<T>` turn a JSON `null` into `undefined` for
531
+ `Option<T>` and optional fields. On the way out, `JSON.stringify` leaves `undefined` fields
532
+ out, so a field that was sent as `null` disappears from the body. A body that changes a record
533
+ (`PATCH`) is a `Patch<T>` from `@evobug_com/safe-ts-std/patch`: each field left out (or `keep`),
534
+ cleared (`clear`, sent as `null`) or set, one spelling each (guide: Absence, "Sending \"clear
535
+ this field\""; Proof types, "Patch<T>"). Another explicit `null` the protocol needs is
536
+ `jsonNull` (JSON guide, "Keeping a JSON null").
537
+
538
+ ```ts bad no-null no-unchecked-cast unhandled-failure
539
+ export type Issue = { readonly id: number; readonly dueDate: string | null };
540
+
541
+ export function readIssue(text: string): Issue {
542
+ return JSON.parse(text) as Issue;
543
+ }
544
+
545
+ export function clearDueDate(issue: Issue): string {
546
+ return JSON.stringify({ id: issue.id, dueDate: null });
547
+ }
548
+ ```
549
+
550
+ ```ts good
551
+ import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
552
+ import { clear, type Patch } from "@evobug_com/safe-ts-std/patch";
553
+ import type { Option } from "@evobug_com/safe-ts-std/result";
554
+
555
+ export type Issue = { readonly id: number; readonly dueDate: Option<string> };
556
+
557
+ export function readIssue(text: string): JsonResult<Issue> {
558
+ return parseJson<Issue>(text);
559
+ }
560
+
561
+ /** The server clears a field it receives as `null`; a missing key leaves it as it is. */
562
+ export function clearDueDate(issue: Issue): string {
563
+ const body: Patch<Issue> = { id: issue.id, dueDate: clear };
564
+ return JSON.stringify(body);
565
+ }
566
+ ```
567
+
568
+ - In a `Patch<T>`, `undefined` never clears a field, and only a field that may be missing can be
569
+ cleared (`{ id: clear }` doesn't compile). `JSON.stringify` of it isn't reported: the object
570
+ is its own wire form.
571
+ - `jsonNull`, `JsonNull` and `clear` belong to data that goes out (a request body) or a type the
572
+ protocol defines that way. Inside the app, "asked and there is none" is an `Option` (or an
573
+ `Enum` variant when it must differ from "not loaded"), never `Option<T | JsonNull>`.
574
+ - A transport adapter that rewrites every `undefined` into `null` on the way out (and back on
575
+ the way in) is a bridge, not the target: it gives the code two spellings of "clear", and a
576
+ stray `undefined` clears data on the server. If the plan uses one, the architecture
577
+ document says so and says when it goes.
578
+ - Before changing what a body sends, record what it sends today (see
579
+ [behaviour.md](behaviour.md)): a key that was `null` and is now missing is a different
580
+ request for a server that tells them apart.
581
+
582
+ ## JSON and storage
583
+
584
+ `JSON.parse(text) as T` believes the text. `parseJson<T>` checks it and returns a `Result`.
585
+ With the browser pack, `getItem(localStorage, key)` returns an `Option<string>` and
586
+ `setItem(...)` a `Result` (a full storage is a value to check).
587
+
588
+ ```ts bad unhandled-failure no-unchecked-cast no-null
589
+ type Draft = { readonly title: string; readonly body: string };
590
+
591
+ export function loadDraft(): Draft | null {
592
+ const text = localStorage.getItem("draft");
593
+ return text === null ? null : (JSON.parse(text) as Draft);
594
+ }
595
+
596
+ export function saveDraft(draft: Draft): void {
597
+ localStorage.setItem("draft", JSON.stringify(draft));
598
+ }
599
+ ```
600
+
601
+ ```ts good
602
+ import { getItem, setItem } from "@evobug_com/safe-ts-feature-browser/storage";
603
+ import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
604
+ import type { Option, Result } from "@evobug_com/safe-ts-std/result";
605
+
606
+ type Draft = { readonly title: string; readonly body: string };
607
+
608
+ /** No saved draft is `undefined`; a saved one that doesn't fit `Draft` is an error. */
609
+ export function loadDraft(): JsonResult<Option<Draft>> {
610
+ const text = getItem(localStorage, "draft");
611
+ return text === undefined ? undefined : parseJson<Draft>(text);
612
+ }
613
+
614
+ export function saveDraft(draft: Draft): Result<void, unknown> {
615
+ return setItem(localStorage, "draft", JSON.stringify(draft));
616
+ }
617
+ ```
618
+
619
+ Read with `validate`, but write back the raw object when another owner keeps fields of its own
620
+ in the same place (`history.state`): `validate<T>` drops the keys `T` doesn't list.
621
+
622
+ ## A cast
623
+
624
+ `as T` on data from outside is a guess; on a literal it is usually a missing annotation; `!`
625
+ on an index or a lookup hides the case the type warns about. Each has a better form, and none
626
+ of them is a new `as`.
627
+
628
+ - Outside data: `validate<T>(value)` / `parseJson<T>(text)`.
629
+ - A literal that should have a type: annotate the variable (`const x: T = ...`) or use
630
+ `satisfies T`.
631
+ - A DOM element: the browser pack's `querySelector(form, "[name=email]", HTMLInputElement)`,
632
+ checked with `instanceof` and typed by the class (`undefined` when missing or of another
633
+ class), or in Vue `useElement` (see the Vue catalogue).
634
+ - A value no check fits, that another part of the same program made (a worker's message):
635
+ `trust<T>(value)`, with a reason comment ([A trusted boundary](#a-trusted-boundary)).
636
+ - A brand (`Html`, `SafeUrl`, `RegexSource`, `Ascii`): only its constructors make one
637
+ (`escapeHtml` or a sanitizer declared with `defineSanitizer`, `safeHref` / `safeUrl`,
638
+ `escapeRegExp`, `isAscii` / `asciiOf`). `as Html` is `brand-constructor`, an error (guide:
639
+ Proof types).
640
+ - `items[i]!`: see [An index read](#an-index-read).
641
+ - A library's loose type: the patterns in the guide's "Typing without casts" page (module
642
+ augmentation, a precise signature over a loose implementation).
643
+
644
+ ```ts bad no-unchecked-cast
645
+ type Settings = { readonly theme: "light" | "dark"; readonly fontSize: number };
646
+
647
+ export function readSettings(message: MessageEvent): Settings {
648
+ return message.data as Settings;
649
+ }
650
+ ```
651
+
652
+ ```ts good
653
+ import { type JsonResult, validate } from "@evobug_com/safe-ts-std/json";
654
+
655
+ type Settings = { readonly theme: "light" | "dark"; readonly fontSize: number };
656
+
657
+ export function readSettings(message: MessageEvent): JsonResult<Settings> {
658
+ return validate<Settings>(message.data);
659
+ }
660
+ ```
661
+
662
+ `validate<T>` takes types declared in the project: imported by name (relatively or through a
663
+ tsconfig `paths` alias), and namespace members such as a generated `Backend.Models.User`, also
664
+ global ones from a declaration file. Not package types, global types from `@types/...` or
665
+ `declare module "..."` blocks ([tool-gaps.md](tool-gaps.md#rules-and-the-checker)).
666
+
667
+ ## A hand-written type guard
668
+
669
+ A `value is T` guard that tests three fields of a type with twenty is a cast the checker can't
670
+ see: it trusts the guard's body. Use `validate<T>`, which tests every field. With the
671
+ idiomatic layer on, `partial-type-guard` reports a `value is T` guard over `unknown` that doesn't
672
+ look at every required field of `T`.
673
+
674
+ ```ts bad partial-type-guard
675
+ type User = { readonly id: number; readonly name: string; readonly email: string };
676
+
677
+ export function isUser(value: unknown): value is User {
678
+ return typeof value === "object" && value !== null && "id" in value;
679
+ }
680
+ ```
681
+
682
+ ```ts good
683
+ import { type JsonResult, validate } from "@evobug_com/safe-ts-std/json";
684
+
685
+ type User = { readonly id: number; readonly name: string; readonly email: string };
686
+
687
+ export function readUser(value: unknown): JsonResult<User> {
688
+ return validate<User>(value);
689
+ }
690
+ ```
691
+
692
+ A guard is fine when it tests everything its type promises (guide: Typing without casts, "A
693
+ type guard that returns a mapped type"), for example over a type `validate` can't take; the
694
+ rule accepts it.
695
+
696
+ ## An index read
697
+
698
+ With `noUncheckedIndexedAccess`, `items[i]` is `T | undefined`. Give the missing case a value,
699
+ or let the checker see the bound: `items[i]!` inside `for (let i = 0; i < items.length; i++)`
700
+ is accepted (rule page `no-unchecked-cast` lists the shapes).
701
+
702
+ ```ts bad no-unchecked-cast
703
+ export function firstWord(text: string): string {
704
+ return text.split(" ")[0]!;
705
+ }
706
+ ```
707
+
708
+ ```ts good
709
+ export function firstWord(text: string): string {
710
+ const [first] = text.split(" ");
711
+ return first ?? "";
712
+ }
713
+ ```
714
+
715
+ Turn both flags (`noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`) on at the start, not
716
+ at the end: their errors show up in the code each builder touches, instead of all at once after
717
+ the merge, and a type-aware oxlint stops calling the `!` unnecessary.
718
+
719
+ ## An optional key
720
+
721
+ Under `exactOptionalPropertyTypes`, `key?: T` refuses an explicit `undefined`, so
722
+ `{ id, delivery: x === "pickup" ? undefined : x }` stops compiling. Leave the key out. The
723
+ recommended form is a conditional spread of a one-key literal,
724
+ `...(x === undefined ? {} : { x })`, also inside a nested object or an argument (guide:
725
+ Absence, "Dropping an optional key"):
726
+
727
+ ```ts good
728
+ import type { Option } from "@evobug_com/safe-ts-std/result";
729
+
730
+ type Callbacks = { readonly onAccept?: () => void; readonly onCancel?: () => void };
731
+
732
+ declare function openDialog(options: { readonly title: string; readonly callbacks: Callbacks }): void;
733
+
734
+ export function confirm(title: string, onAccept: Option<() => void>, onCancel: Option<() => void>): void {
735
+ openDialog({
736
+ title,
737
+ callbacks: {
738
+ ...(onAccept === undefined ? {} : { onAccept }),
739
+ ...(onCancel === undefined ? {} : { onCancel }),
740
+ },
741
+ });
742
+ }
743
+ ```
744
+
745
+ - `stable-shape` accepts one such spread in any literal, and two where the type the literal is
746
+ written for declares both keys optional. With three or more (eight shapes), and for objects
747
+ read in a hot loop, declare the fields `Option<T>` and always write them, `x: undefined`
748
+ included. The same for a Vue component's optional props a template always passes
749
+ (`:x="maybe"`): declare them `x?: Option<T>`.
750
+ - To drop keys from an existing object, `omit(settings, "theme")` (`@evobug_com/safe-ts-std/dict`),
751
+ not `delete` or `{ ...settings, theme: undefined }`.
752
+ - Two object literals, one without the key, are fine too when the branches differ anyway:
753
+
754
+ ```ts good
755
+ type Delivery = "pickup" | "courier" | "post";
756
+
757
+ export type Order = { readonly id: string; readonly delivery?: Exclude<Delivery, "pickup"> };
758
+
759
+ export function order(id: string, delivery: Delivery): Order {
760
+ return delivery === "pickup" ? { id } : { id, delivery };
761
+ }
762
+ ```
763
+
764
+ Decide the form for the component library's optional props in the foundation step, once
765
+ ([order-and-gates.md](order-and-gates.md)).
766
+
767
+ ## A table keyed by server data
768
+
769
+ `LABELS[state]` with `state` from the server reads `undefined` for a value this build doesn't
770
+ know (a new state added on the server), and the page crashes on `.tooltip of undefined`. Look
771
+ it up with `getOwn(table, key, fallback)`: the fallback is typed like the table's values, so a
772
+ literal fallback doesn't widen them.
773
+
774
+ ```ts bad no-object-dictionary
775
+ type State = "open" | "closed";
776
+
777
+ const LABELS: Record<string, string> = { open: "Open", closed: "Closed" };
778
+
779
+ export function stateLabel(state: string): string {
780
+ return LABELS[state] ?? "Unknown";
781
+ }
782
+ ```
783
+
784
+ ```ts good
785
+ import { getOwn } from "@evobug_com/safe-ts-std/dict";
786
+
787
+ type State = "open" | "closed";
788
+
789
+ const LABELS: Record<State, string> = { open: "Open", closed: "Closed" };
790
+
791
+ export function stateLabel(state: string): string {
792
+ return getOwn(LABELS, state, "Unknown");
793
+ }
794
+ ```
795
+
796
+ `satisfies Record<State, string>` (or the annotation) checks that every state this build knows
797
+ has a row; `getOwn` handles the ones it doesn't, and `constructor` or `toString` as a key.
798
+ Without the third argument it returns an `Option`.
799
+
800
+ ## A server value from a list that can grow
801
+
802
+ A status or type the server sends from a list it may extend: typed as a union of the strings
803
+ this build knows, `parseJson` fails the whole response on a new one; typed as `string`, a lookup
804
+ answers `undefined` for it. `Open<K>` (`@evobug_com/safe-ts-std/open`) keeps both cases:
805
+ `parseJson` / `validate` give a string `K` lists its variant and any other string `Unknown`,
806
+ `match` needs an `Unknown` handler, and `lookup(table, value, fallback)` reads an exhaustive
807
+ table with a fallback for `Unknown` (`TABLE[state.tag]` doesn't compile). Use `getOwn` for a
808
+ dictionary keyed by any string, `Open` + `lookup` for a field the server fills from a list.
809
+
810
+ ```ts good
811
+ import { match } from "@evobug_com/safe-ts-std/enum";
812
+ import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
813
+ import { type Known, lookup, type Open } from "@evobug_com/safe-ts-std/open";
814
+
815
+ export type Issue = { readonly title: string; readonly state: Open<"todo" | "doing" | "done"> };
816
+
817
+ const ICONS = { todo: "circle", doing: "half", done: "check" } satisfies Record<Known<Issue["state"]>, string>;
818
+
819
+ export function readIssue(text: string): JsonResult<Issue> {
820
+ return parseJson<Issue>(text);
821
+ }
822
+
823
+ export function label(issue: Issue): string {
824
+ return match(issue.state, {
825
+ todo: () => "To do",
826
+ doing: () => "Doing",
827
+ done: () => "Done",
828
+ Unknown: ({ value }) => value,
829
+ });
830
+ }
831
+
832
+ export function icon(issue: Issue): string {
833
+ return lookup(ICONS, issue.state, "question");
834
+ }
835
+ ```
836
+
837
+ `value` is the text as it came: send `issue.state.value` back to the server, not the object
838
+ (`JSON.stringify` of it writes `{"tag":…,"value":…}`). `toOpen(known, text)` makes one from text
839
+ that doesn't come through `parseJson` (a route parameter).
840
+
841
+ ## Base64
842
+
843
+ `btoa` throws for a character above U+00FF, so `btoa(name)` on user text fails on the first
844
+ "é" (`unhandled-failure`; `btoa` of digits or of text written out is accepted). `toBase64` from
845
+ `@evobug_com/safe-ts-std/base64` encodes any string as UTF-8 and can't fail; `fromBase64` and
846
+ `fromBase64Bytes` return a `Result` (`not base64`, `not UTF-8`). `{ alphabet: "base64url" }`
847
+ gives the URL-safe alphabet.
848
+
849
+ ```ts bad unhandled-failure
850
+ export function avatarKey(name: string): string {
851
+ return btoa(name);
852
+ }
853
+ ```
854
+
855
+ ```ts good
856
+ import { toBase64 } from "@evobug_com/safe-ts-std/base64";
857
+
858
+ export function avatarKey(name: string): string {
859
+ return toBase64(name, { alphabet: "base64url" });
860
+ }
861
+ ```
862
+
863
+ Where the text is ASCII by contract (an id, a token), keep `btoa` and prove it:
864
+ `isAscii(id)` (`@evobug_com/safe-ts-std/ascii`) narrows the value to `Ascii`, `asciiOf(n)` makes
865
+ one from a number, and `btoa` of an `Ascii` isn't reported. The encoded text stays the same.
866
+
867
+ For text with characters between U+0080 and U+00FF, `toBase64` writes their UTF-8 bytes where
868
+ `btoa` wrote one byte each: the encoded text changes. Check what reads it (a server decoding it
869
+ as Latin-1) before switching, and say so in the hand-off report
870
+ ([behaviour.md](behaviour.md)). Don't wrap `btoa` in `unsafe(...)` to keep the old output
871
+ unless the architecture document lists it.
872
+
873
+ ## A trusted boundary
874
+
875
+ A value no check fits, or not worth one, that another part of the same program made (a
876
+ worker of the same build that posts only one message type): `trust<T>(value)` from
877
+ `@evobug_com/safe-ts-std/result`. It does nothing at runtime, is searchable, and `safe-ts check`
878
+ counts it in its escape-hatches line, so it replaces the `as T` and the overload or guard that
879
+ hid one. Data from outside the program (the network, storage, a file) is validated instead.
880
+
881
+ ```ts bad no-unchecked-cast
882
+ type Progress = { readonly done: number; readonly total: number };
883
+
884
+ export function onProgress(event: MessageEvent<unknown>, show: (progress: Progress) => void): void {
885
+ show(event.data as Progress);
886
+ }
887
+ ```
888
+
889
+ ```ts good
890
+ import { trust } from "@evobug_com/safe-ts-std/result";
891
+
892
+ type Progress = { readonly done: number; readonly total: number };
893
+
894
+ export function onProgress(event: MessageEvent<unknown>, show: (progress: Progress) => void): void {
895
+ // The worker posts only `Progress` messages (worker.ts, same build).
896
+ show(trust<Progress>(event.data));
897
+ }
898
+ ```
899
+
900
+ Every `trust` is listed in the architecture document's boundaries section, with the reason
901
+ ([escape-hatches.md](escape-hatches.md)).
902
+
903
+ ## Strict code with legacy callers that pass null
904
+
905
+ A function migrated before its callers still gets `null` from the legacy ones. `LegacyNull`
906
+ (`@evobug_com/safe-ts-std/result`) is the documented bridge: `Option<T> | LegacyNull` accepts
907
+ the `null` without one written in the strict file, and is counted. Drop it once no caller passes
908
+ `null`; a `null` that means something on the wire is `JsonNull`, not this.
909
+
910
+ ```ts bad no-null
911
+ export function heading(title: string | null | undefined): string {
912
+ return title ?? "Untitled";
913
+ }
914
+ ```
915
+
916
+ ```ts good
917
+ import type { LegacyNull, Option } from "@evobug_com/safe-ts-std/result";
918
+
919
+ // Legacy callers (src/reports, marked legacy) still pass `null` for "no title". Goes with them.
920
+ export function heading(title: Option<string> | LegacyNull): string {
921
+ return title ?? "Untitled";
922
+ }
923
+ ```
924
+
925
+ Don't invent a project-local bridge type (`UiLegacyNull`, `Nullable<T>`): the census and
926
+ `safe-ts check` count `LegacyNull` and not those.
927
+
928
+ ## Command-line arguments
929
+
930
+ `parseArgs` from `node:util` throws on an unknown option or a missing value. With the Node pack
931
+ (`@evobug_com/safe-ts-feature-node`), its safe version returns a `Result`, with the values
932
+ typed by the options as Node's own.
933
+
934
+ ```ts bad unhandled-failure
935
+ import { parseArgs } from "node:util";
936
+
937
+ export function portText(): string {
938
+ const { values } = parseArgs({ options: { port: { type: "string" } } });
939
+ return values.port ?? "8080";
940
+ }
941
+ ```
942
+
943
+ ```ts good
944
+ import { parseArgs } from "@evobug_com/safe-ts-feature-node/util";
945
+ import { q, type Result } from "@evobug_com/safe-ts-std/result";
946
+
947
+ export function portText(): Result<string, Error> {
948
+ const parsed = q(parseArgs({ options: { port: { type: "string" } } }));
949
+ return parsed.values.port ?? "8080";
950
+ }
951
+ ```
952
+
953
+ ## IndexedDB
954
+
955
+ The request-and-callback API (`indexedDB.open(...)`, `onsuccess`, `onerror`, `onupgradeneeded`)
956
+ throws in some calls and reports in callbacks in others. The browser pack's
957
+ `@evobug_com/safe-ts-feature-browser/indexeddb` settles each request as a `Promise<Result>` (or a
958
+ `Result` for the calls that only throw), with typed errors: `open`, `createObjectStore` (in
959
+ `upgrade`), `transaction`, `objectStore`, `get` (with a validator), `getGuarded`, `put`,
960
+ `deleteKey`, `clear`, `commit`. A real app keeps the errors typed (an `Enum` of the kinds the
961
+ UI handles); `describeError` turns any of them into one line, which is enough here.
962
+
963
+ ```ts good
964
+ import { commit, createObjectStore, get, objectStore, open, put, transaction } from "@evobug_com/safe-ts-feature-browser/indexeddb";
965
+ import { validate } from "@evobug_com/safe-ts-std/json";
966
+ import { describeError, type Option, q, type Result } from "@evobug_com/safe-ts-std/result";
967
+
968
+ type Draft = { readonly id: string; readonly text: string };
969
+
970
+ const openDrafts = () =>
971
+ open(indexedDB, "app", { version: 1, upgrade: (database) => createObjectStore(database, "drafts", { keyPath: "id" }) });
972
+
973
+ export async function saveDraft(draft: Draft): Promise<Result<void, string>> {
974
+ const db = q(await openDrafts(), describeError);
975
+ const tx = q(transaction(db, "drafts", "readwrite"), describeError);
976
+ const store = q(objectStore(tx, "drafts"), describeError);
977
+ q(await put(store, draft), describeError);
978
+ return q(await commit(tx), describeError);
979
+ }
980
+
981
+ export async function loadDraft(id: string): Promise<Result<Option<Draft>, string>> {
982
+ const db = q(await openDrafts(), describeError);
983
+ const tx = q(transaction(db, "drafts"), describeError);
984
+ const store = q(objectStore(tx, "drafts"), describeError);
985
+ return q(await get(store, id, (value) => validate<Draft>(value)), describeError);
986
+ }
987
+ ```
988
+
989
+ Call `commit(tx)` right after the last request: awaiting something else in between lets the
990
+ transaction finish without you (`TransactionInactiveError`).
991
+
992
+ ## A bug inside a Result-returning call
993
+
994
+ `unsafeAsync(() => search(text))` around a function of your own that returns a `Result` merges
995
+ its typed `Err` with whatever it throws by mistake into one `Err<unknown>`, so a bug is shown
996
+ to the user as an ordinary failure. Pass `Panic`: the throw becomes a `Panic` (not an `Err`),
997
+ and the returned `Err` keeps its type (guide: Errors, "When you call code that throws").
998
+
999
+ ```ts good
1000
+ import { isErr, isPanic, Panic, type Result, unsafeAsync } from "@evobug_com/safe-ts-std/result";
1001
+
1002
+ declare function send(message: string): Promise<Result<void, "refused">>;
1003
+
1004
+ export async function deliver(message: string): Promise<string> {
1005
+ // A throw from send() is a bug: kept apart from the "refused" it returns.
1006
+ const sent = await unsafeAsync(() => send(message), Panic);
1007
+ if (isPanic(sent)) return `bug: ${String(sent.reason)}`;
1008
+ if (isErr(sent)) return `not delivered: ${sent.error}`;
1009
+ return "delivered";
1010
+ }
1011
+ ```
1012
+
1013
+ Better still, don't wrap your own code at all: if it can throw, that is the bug to fix. With the
1014
+ idiomatic layer on, `unsafe-project-call` reports `unsafe` / `unsafeAsync` without `Panic`
1015
+ around a call of the project's own function that the checker finds nothing to throw in.
1016
+
1017
+ ## panic on a loading state
1018
+
1019
+ `panic` is for invariants nothing can handle (a table built at load time with a name listed
1020
+ twice). A store read before its data arrived is a state of the page, not an invariant: show a
1021
+ wait (an `AsyncState`, `Option`), don't crash. With the idiomatic layer on, `panic-on-loading`
1022
+ reports a `panic` under a condition that names a loading flag (`hydrated`, `isLoading`, ...) or
1023
+ a `Loading` / `Idle` variant; it goes by names, so a `panic` on a loading state under another
1024
+ name is left to review.
1025
+
1026
+ ```ts bad panic-on-loading
1027
+ import { type Option, panic } from "@evobug_com/safe-ts-std/result";
1028
+
1029
+ type Session = { readonly hydrated: boolean; readonly user: Option<{ readonly name: string }> };
1030
+
1031
+ export function userName(session: Session): string {
1032
+ if (!session.hydrated || session.user === undefined) panic("the session is not hydrated");
1033
+ return session.user.name;
1034
+ }
1035
+ ```
1036
+
1037
+ ```ts good
1038
+ import type { Option } from "@evobug_com/safe-ts-std/result";
1039
+
1040
+ type Session = { readonly hydrated: boolean; readonly user: Option<{ readonly name: string }> };
1041
+
1042
+ export function userName(session: Session): Option<string> {
1043
+ return session.user?.name;
1044
+ }
1045
+ ```
1046
+
1047
+ ## Casts in tests
1048
+
1049
+ `as unknown as Service` and `as never` in tests say a value has a type without anything to
1050
+ back it. `@evobug_com/safe-ts-std/testing` names each need: `fixture<T>(fields)` for a value of a
1051
+ big type with the fields the test needs, `testDouble<T>(fields)` for a fake that throws when
1052
+ code reads a field it wasn't given, `unchecked<T>(value)` for the wrong type on purpose, and
1053
+ `expectPresent(value)` for a lookup the test knows succeeds (guide: Testing, "Partial and fake
1054
+ values"). They are reported outside test files (`test-only-helper`). In test files a cast is
1055
+ reported by `no-unchecked-cast`, whose help there names these helpers; where a project turns
1056
+ that rule off for its tests, `cast-in-test` (idiomatic) still reports `as unknown as T` and
1057
+ `as never`.
1058
+
1059
+ ```ts good
1060
+ import assert from "node:assert/strict";
1061
+ import { test } from "node:test";
1062
+
1063
+ import { fixture } from "@evobug_com/safe-ts-std/testing";
1064
+
1065
+ type Invoice = { readonly number: string; readonly total: number; readonly customer: { readonly name: string; readonly email: string } };
1066
+
1067
+ function greeting(invoice: Invoice): string {
1068
+ return `Dear ${invoice.customer.name}`;
1069
+ }
1070
+
1071
+ test("the greeting uses the customer's name", () => {
1072
+ assert.equal(greeting(fixture<Invoice>({ customer: { name: "Ada" } })), "Dear Ada");
1073
+ });
1074
+ ```