@evobug_com/safe-ts-skill 0.0.0-stage → 0.5.1
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.
- package/LICENSE-APACHE +201 -0
- package/LICENSE-MIT +21 -0
- package/README.md +15 -2
- package/install.mjs +86 -0
- package/package.json +35 -4
- package/safe-ts-migrate/SKILL.md +178 -0
- package/safe-ts-migrate/references/architecture.md +146 -0
- package/safe-ts-migrate/references/behaviour.md +86 -0
- package/safe-ts-migrate/references/census.md +136 -0
- package/safe-ts-migrate/references/escape-hatches.md +72 -0
- package/safe-ts-migrate/references/final-pass.md +46 -0
- package/safe-ts-migrate/references/fix-the-design.md +87 -0
- package/safe-ts-migrate/references/order-and-gates.md +101 -0
- package/safe-ts-migrate/references/patterns-core.md +2229 -0
- package/safe-ts-migrate/references/patterns-react.md +266 -0
- package/safe-ts-migrate/references/patterns-vue.md +713 -0
- package/safe-ts-migrate/references/review-checklist.md +70 -0
- package/safe-ts-migrate/references/templates.md +260 -0
- package/safe-ts-migrate/references/tool-gaps.md +394 -0
- package/safe-ts-migrate/scripts/census.mjs +870 -0
- package/safe-ts-migrate/scripts/safe-ts.mjs +79 -0
|
@@ -0,0 +1,2229 @@
|
|
|
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 method in an interface](#a-method-in-an-interface)
|
|
39
|
+
- [A failure behind an interface](#a-failure-behind-an-interface)
|
|
40
|
+
- [A list spread into Math.max or push](#a-list-spread-into-mathmax-or-push)
|
|
41
|
+
- [A "not found" answer used as a value](#a-not-found-answer-used-as-a-value)
|
|
42
|
+
- [A promise used as its value](#a-promise-used-as-its-value)
|
|
43
|
+
- [A value used after it was used up](#a-value-used-after-it-was-used-up)
|
|
44
|
+
- [Text given to a sink](#text-given-to-a-sink)
|
|
45
|
+
- [A constructor that calls an overridable method](#a-constructor-that-calls-an-overridable-method)
|
|
46
|
+
- [A table keyed by server data](#a-table-keyed-by-server-data)
|
|
47
|
+
- [A server value from a list that can grow](#a-server-value-from-a-list-that-can-grow)
|
|
48
|
+
- [Base64](#base64)
|
|
49
|
+
- [A built-in that throws on data](#a-built-in-that-throws-on-data)
|
|
50
|
+
- [A trusted boundary](#a-trusted-boundary)
|
|
51
|
+
- [Strict code with legacy callers that pass null](#strict-code-with-legacy-callers-that-pass-null)
|
|
52
|
+
- [Command-line arguments](#command-line-arguments)
|
|
53
|
+
- [IndexedDB](#indexeddb)
|
|
54
|
+
- [A bug inside a Result-returning call](#a-bug-inside-a-result-returning-call)
|
|
55
|
+
- [panic on a loading state](#panic-on-a-loading-state)
|
|
56
|
+
- [A method handed over by name](#a-method-handed-over-by-name)
|
|
57
|
+
- [A parameter the function changes](#a-parameter-the-function-changes)
|
|
58
|
+
- [Casts in tests](#casts-in-tests)
|
|
59
|
+
- [A function result the checker cannot read](#a-function-result-the-checker-cannot-read)
|
|
60
|
+
|
|
61
|
+
## A function that throws
|
|
62
|
+
|
|
63
|
+
A caller can't see that `findName` throws, so it doesn't handle it. Return the error, named as
|
|
64
|
+
an `Enum` of the kinds the caller handles. `safe-ts migrate throw-to-result <dir>` does the first
|
|
65
|
+
step for the functions it can convert safely (guide: Adopting SAFE-TS, "Migrating with
|
|
66
|
+
codemods"): it keeps the thrown class (`err(new NotFound(...))`). Name the kinds after it.
|
|
67
|
+
|
|
68
|
+
```ts bad no-throw
|
|
69
|
+
export class NotFound extends Error {}
|
|
70
|
+
|
|
71
|
+
const names = new Map([["1", "Ada"]]);
|
|
72
|
+
|
|
73
|
+
export function findName(id: string): string {
|
|
74
|
+
const name = names.get(id);
|
|
75
|
+
if (name === undefined) throw new NotFound(`no user ${id}`);
|
|
76
|
+
return name;
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```ts good
|
|
81
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
82
|
+
import { err, type Result } from "@evobug_com/safe-ts-std/result";
|
|
83
|
+
|
|
84
|
+
export type LookupError = Enum<{ NotFound: { id: string } }>;
|
|
85
|
+
export const LookupError = constructors<LookupError>();
|
|
86
|
+
|
|
87
|
+
const names = new Map([["1", "Ada"]]);
|
|
88
|
+
|
|
89
|
+
export function findName(id: string): Result<string, LookupError> {
|
|
90
|
+
const name = names.get(id);
|
|
91
|
+
if (name === undefined) return err(LookupError.NotFound({ id }));
|
|
92
|
+
return name;
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
When a failure should end a whole request, job or command (not be handled by the next
|
|
97
|
+
caller), throw a subclass of `PropagateError` and catch it in one place at the top (guide:
|
|
98
|
+
Errors, "When the whole request should stop"). `throw new Error(...)` is never the answer.
|
|
99
|
+
|
|
100
|
+
## Passing an error up
|
|
101
|
+
|
|
102
|
+
`if (isErr(x)) return x` after every call is correct and long. `q(...)` says it in one line,
|
|
103
|
+
and the build turns it into that `if`. When the error type changes on the way up, give `q` the
|
|
104
|
+
mapping, or use `mapErr` outside `q` (guide: Errors, "Pass an error up with q(...)"). With the
|
|
105
|
+
idiomatic layer on, `prefer-q` reports the `if (isErr(x)) return x` (its quick fix writes the
|
|
106
|
+
`q`; `safe-ts fix prefer-q src/` applies it everywhere, as a diff to review first), and
|
|
107
|
+
`prefer-map-err` the error re-wrapped by hand. Not in files a Vite config imports: they run
|
|
108
|
+
without the transform, so the `if` stays there.
|
|
109
|
+
|
|
110
|
+
```ts bad prefer-map-err prefer-q
|
|
111
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
112
|
+
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
113
|
+
|
|
114
|
+
type Upload = { readonly size: number };
|
|
115
|
+
type CheckError = Enum<{ TooLarge: { max: number } }>;
|
|
116
|
+
export type UploadError = Enum<{ Invalid: { problem: CheckError }; StoreFull: {} }>;
|
|
117
|
+
export const UploadError = constructors<UploadError>();
|
|
118
|
+
|
|
119
|
+
declare function checkUpload(size: number): Result<Upload, CheckError>;
|
|
120
|
+
declare function storeUpload(upload: Upload): Result<string, UploadError>;
|
|
121
|
+
|
|
122
|
+
export function startUpload(size: number): Result<string, UploadError> {
|
|
123
|
+
const upload = checkUpload(size);
|
|
124
|
+
if (isErr(upload)) return err(UploadError.Invalid({ problem: upload.error }));
|
|
125
|
+
const id = storeUpload(upload);
|
|
126
|
+
if (isErr(id)) return id;
|
|
127
|
+
return id;
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
```ts good
|
|
132
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
133
|
+
import { q, type Result } from "@evobug_com/safe-ts-std/result";
|
|
134
|
+
|
|
135
|
+
type Upload = { readonly size: number };
|
|
136
|
+
type CheckError = Enum<{ TooLarge: { max: number } }>;
|
|
137
|
+
export type UploadError = Enum<{ Invalid: { problem: CheckError }; StoreFull: {} }>;
|
|
138
|
+
export const UploadError = constructors<UploadError>();
|
|
139
|
+
|
|
140
|
+
declare function checkUpload(size: number): Result<Upload, CheckError>;
|
|
141
|
+
declare function storeUpload(upload: Upload): Result<string, UploadError>;
|
|
142
|
+
|
|
143
|
+
const invalid = (problem: CheckError): UploadError => UploadError.Invalid({ problem });
|
|
144
|
+
|
|
145
|
+
export function startUpload(size: number): Result<string, UploadError> {
|
|
146
|
+
const upload = q(checkUpload(size), invalid);
|
|
147
|
+
const id = q(storeUpload(upload));
|
|
148
|
+
return id;
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`q(...)` is a statement of its own (`const x = q(...)`, `x = q(...)`, `q(...);`,
|
|
153
|
+
`return q(...)`), in a function that returns a `Result`. The error it passes on must be one the
|
|
154
|
+
function declares: `q(parse(text))` with `parse` returning `Result<number, "bad-number">`, in a
|
|
155
|
+
function declaring `Result<number, "other">`, returns an error no caller's `match` expects, and
|
|
156
|
+
`tsc` can't see it (`q` gives it `T`). `q-undeclared-error` (an error) reports it where both
|
|
157
|
+
sides are written; declare the error, or map it with `q(result, (error): Declared => ...)`. It needs the build transform: the
|
|
158
|
+
Vite plugin, or `node --import @evobug_com/safe-ts-transform/register` for code Node runs.
|
|
159
|
+
|
|
160
|
+
## Requests return a Result
|
|
161
|
+
|
|
162
|
+
A raw `fetch` can wait forever, rejects on a network failure, and `response.json()` gives a
|
|
163
|
+
value nobody checked (`unknown` with std's strict-lib, `any` without it), which a cast then
|
|
164
|
+
believes. A request function owns all three: a time limit and the caller's signal, the failure
|
|
165
|
+
as a typed error, and the body checked against the type.
|
|
166
|
+
|
|
167
|
+
```ts bad fetch-signal unhandled-failure no-unchecked-cast
|
|
168
|
+
export type User = { readonly id: number; readonly name: string };
|
|
169
|
+
|
|
170
|
+
export async function fetchUser(id: number): Promise<User> {
|
|
171
|
+
const response = await fetch(`/api/users/${id}`);
|
|
172
|
+
return (await response.json()) as User;
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
```ts good
|
|
177
|
+
import { fetch, json } from "@evobug_com/safe-ts-feature-browser/fetch";
|
|
178
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
179
|
+
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
|
|
180
|
+
import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
|
|
181
|
+
|
|
182
|
+
export type User = { readonly id: number; readonly name: string };
|
|
183
|
+
|
|
184
|
+
export type RequestError = Enum<{
|
|
185
|
+
Network: { reason: string };
|
|
186
|
+
Status: { status: number };
|
|
187
|
+
Body: { problem: JsonError };
|
|
188
|
+
}>;
|
|
189
|
+
export const RequestError = constructors<RequestError>();
|
|
190
|
+
|
|
191
|
+
const network = (cause: unknown): RequestError => RequestError.Network({ reason: String(cause) });
|
|
192
|
+
const body = (problem: JsonError): RequestError => RequestError.Body({ problem });
|
|
193
|
+
|
|
194
|
+
export async function fetchUser(id: number, signal: AbortSignal): Promise<Result<User, RequestError>> {
|
|
195
|
+
const limit = AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
|
|
196
|
+
const response = q(await fetch(`/api/users/${id}`, { signal: limit }), network);
|
|
197
|
+
if (!response.ok) return err(RequestError.Status({ status: response.status }));
|
|
198
|
+
const data: unknown = q(await json(response), network);
|
|
199
|
+
return q(validate<User>(data), body);
|
|
200
|
+
}
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
- Every request function takes a `signal` (a component's `useTask` passes its own), and adds a
|
|
204
|
+
time limit made per request.
|
|
205
|
+
- The error is an `Enum`, so callers `match` on it: a 422's message shown inline is a
|
|
206
|
+
different variant from a dropped connection, and nothing is lost on the way to the screen.
|
|
207
|
+
- The same shape works around an HTTP client (axios, ky): `unsafeAsync(() => client.get(...))`
|
|
208
|
+
for the rejection, then `validate<T>` on the data. Put one such function per endpoint, or
|
|
209
|
+
one generic `request<T>` whose callers always give `T` (a `Result<unknown, E>` is just
|
|
210
|
+
`unknown`, and `no-unknown-in-result` reports it).
|
|
211
|
+
- With the browser pack enabled, the pack's `fetch` is the safe version of the global, and
|
|
212
|
+
`json(response)` of `response.json()` (guide: Libraries and feature packs).
|
|
213
|
+
- `fetch-signal` reports a bare `fetch(...)` without a `signal`. List the project's own request
|
|
214
|
+
wrapper or axios instance in package.json, `"safe-ts": { "requestFunctions": ["api"] }`, and
|
|
215
|
+
a call of it (or of a method on it, `api.get(url)`) without a `signal` or `timeout` is
|
|
216
|
+
reported too.
|
|
217
|
+
- With the idiomatic layer on, `misplaced-axios-check` reports an `isAxiosError(r.error)` on a
|
|
218
|
+
function that has its own error type: match on that type's variants instead.
|
|
219
|
+
|
|
220
|
+
## Try and catch around your own code
|
|
221
|
+
|
|
222
|
+
A `try` around code of your own hides which call failed and what kind of failure it was. Once
|
|
223
|
+
the functions it calls return `Result`s, the `try` has nothing left to catch, and a `.catch` on a
|
|
224
|
+
`Promise<Result<...>>` catches nothing either (it only looks like handling). Remove both when
|
|
225
|
+
the callee changes, at every caller. The checker helps: `must-use-result` follows a `Result`
|
|
226
|
+
through store members (Pinia setup and options stores), returned objects and factories, and
|
|
227
|
+
reports one that is dropped, `.catch(() => {})` included; with the idiomatic layer on,
|
|
228
|
+
`catch-on-result` reports a `.catch` or a `try` around nothing but calls that return a `Result`
|
|
229
|
+
(not a `try` whose callee also throws a tracked `PropagateError` that this `catch` takes: that
|
|
230
|
+
`try` is a boundary).
|
|
231
|
+
It follows a method through a field or a property declared with its class
|
|
232
|
+
(`this.repo.save()`, `deps.repo.save()`) and through a function declared to return the class
|
|
233
|
+
(`makeRepo().save()`), but can't see one reached through a value typed with an interface or a
|
|
234
|
+
union, a `ref` or a `Map` (rule page `must-use-result`, "What the rule can't see"): search for
|
|
235
|
+
each changed function's name too.
|
|
236
|
+
|
|
237
|
+
```ts bad
|
|
238
|
+
declare function saveDraft(text: string): Promise<void>;
|
|
239
|
+
|
|
240
|
+
export async function onSave(text: string, show: (message: string) => void): Promise<void> {
|
|
241
|
+
try {
|
|
242
|
+
await saveDraft(text);
|
|
243
|
+
show("Saved");
|
|
244
|
+
} catch {
|
|
245
|
+
show("Could not save");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
```ts good
|
|
251
|
+
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
252
|
+
import { isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
253
|
+
|
|
254
|
+
type SaveError = Enum<{ Offline: {}; Conflict: { by: string } }>;
|
|
255
|
+
|
|
256
|
+
declare function saveDraft(text: string): Promise<Result<void, SaveError>>;
|
|
257
|
+
|
|
258
|
+
export async function onSave(text: string, show: (message: string) => void): Promise<void> {
|
|
259
|
+
const saved = await saveDraft(text);
|
|
260
|
+
if (!isErr(saved)) return show("Saved");
|
|
261
|
+
show(
|
|
262
|
+
match(saved.error, {
|
|
263
|
+
Offline: () => "Offline: the draft stays on this device",
|
|
264
|
+
Conflict: ({ by }) => `${by} changed it in the meantime`,
|
|
265
|
+
}),
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
The `try` left behind once `saveDraft` returns a `Result`:
|
|
271
|
+
|
|
272
|
+
```ts bad catch-on-result
|
|
273
|
+
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
274
|
+
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
275
|
+
|
|
276
|
+
type SaveError = Enum<{ Empty: {} }>;
|
|
277
|
+
const SaveError = constructors<SaveError>();
|
|
278
|
+
|
|
279
|
+
async function saveDraft(text: string): Promise<Result<void, SaveError>> {
|
|
280
|
+
return text === "" ? err(SaveError.Empty()) : undefined;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export async function onSave(text: string): Promise<string> {
|
|
284
|
+
let saved: Result<void, SaveError>;
|
|
285
|
+
try {
|
|
286
|
+
saved = await saveDraft(text);
|
|
287
|
+
} catch {
|
|
288
|
+
return "Could not save";
|
|
289
|
+
}
|
|
290
|
+
return isErr(saved) ? match(saved.error, { Empty: () => "Nothing to save" }) : "Saved";
|
|
291
|
+
}
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
A `try` stays where code of someone else's throws and no safe version exists (wrap it in
|
|
295
|
+
`unsafe(...)` with a reason instead, see [escape-hatches.md](escape-hatches.md)), and at a
|
|
296
|
+
harness boundary that runs independent units of work and reports each failure (guide: Errors,
|
|
297
|
+
"When catching everything is right: harness boundaries").
|
|
298
|
+
|
|
299
|
+
## A failure turned into undefined
|
|
300
|
+
|
|
301
|
+
`unwrapOr(result, undefined)`, `.catch(() => undefined)` and `if (isErr(r)) return undefined`
|
|
302
|
+
make a corrupt value look like a missing one. Return the `Result`, with `Option` inside it when
|
|
303
|
+
"missing" is a real answer. `no-swallowed-error` (idiomatic) reports each of these, `.catch(()
|
|
304
|
+
=> {})`, `.catch(() => null)` and `unwrapOr(result, null)` too, and every call of a one-line
|
|
305
|
+
helper that does one of them (an `orNone(parseJson(text))`): don't write one.
|
|
306
|
+
|
|
307
|
+
```ts bad no-swallowed-error
|
|
308
|
+
import { parseJson } from "@evobug_com/safe-ts-std/json";
|
|
309
|
+
import { isErr, type Option } from "@evobug_com/safe-ts-std/result";
|
|
310
|
+
|
|
311
|
+
type Save = { readonly level: number };
|
|
312
|
+
|
|
313
|
+
export function savedLevel(text: string): Option<number> {
|
|
314
|
+
const save = parseJson<Save>(text);
|
|
315
|
+
if (isErr(save)) return undefined;
|
|
316
|
+
return save.level;
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
```ts good
|
|
321
|
+
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
|
|
322
|
+
import { q } from "@evobug_com/safe-ts-std/result";
|
|
323
|
+
|
|
324
|
+
type Save = { readonly level: number };
|
|
325
|
+
|
|
326
|
+
export function savedLevel(text: string): JsonResult<number> {
|
|
327
|
+
const save = q(parseJson<Save>(text));
|
|
328
|
+
return save.level;
|
|
329
|
+
}
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Where a failure really does mean "missing" for this caller, report it first (log it, show it),
|
|
333
|
+
then return `undefined`: the rule accepts a branch that does something with the error.
|
|
334
|
+
|
|
335
|
+
## A sentinel value
|
|
336
|
+
|
|
337
|
+
`''` for "no error", `-1` for "not found" and `0` for "nothing selected" are values of the
|
|
338
|
+
type, so nothing makes the caller test for them. Say what the function returns: `Option<T>`
|
|
339
|
+
for "maybe missing", `Result<void, E>` for a command that can fail, an `Enum` variant when
|
|
340
|
+
"none" carries meaning of its own. With the idiomatic layer on, `sentinel-error` reports the
|
|
341
|
+
`''`-for-no-error case, and `strict-truthiness` the `if (block)` that reads it: a test of a
|
|
342
|
+
string or number for truth hides `""` and `0` along with `undefined`. Compare with what is
|
|
343
|
+
meant (`!== undefined`, `> 0`). Where the value may be `undefined` (an `Option`, `x?:`, `a?.b`),
|
|
344
|
+
the replacement decides both: `x !== undefined && x !== ""` keeps the meaning, `x !== undefined`
|
|
345
|
+
lets `""` through, and `x !== ""` alone is true for `undefined` (`compare-misses-undefined`, an
|
|
346
|
+
error).
|
|
347
|
+
|
|
348
|
+
```ts bad sentinel-error strict-truthiness
|
|
349
|
+
type Wallet = { readonly balance: number };
|
|
350
|
+
|
|
351
|
+
export function buyBlock(wallet: Wallet, price: number): string {
|
|
352
|
+
return price > wallet.balance ? `costs ${price} EUR` : "";
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export function buyTitle(wallet: Wallet, price: number): string {
|
|
356
|
+
const block = buyBlock(wallet, price);
|
|
357
|
+
return block ? `Can't buy: ${block}` : "Buy";
|
|
358
|
+
}
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
```ts good
|
|
362
|
+
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
363
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
364
|
+
|
|
365
|
+
type Wallet = { readonly balance: number };
|
|
366
|
+
|
|
367
|
+
export type BuyBlock = Enum<{ TooExpensive: { missing: number } }>;
|
|
368
|
+
export const BuyBlock = constructors<BuyBlock>();
|
|
369
|
+
|
|
370
|
+
export function buyBlock(wallet: Wallet, price: number): Option<BuyBlock> {
|
|
371
|
+
return price > wallet.balance ? BuyBlock.TooExpensive({ missing: price - wallet.balance }) : undefined;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export function buyTitle(wallet: Wallet, price: number): string {
|
|
375
|
+
return match(buyBlock(wallet, price), {
|
|
376
|
+
TooExpensive: ({ missing }) => `Can't buy: ${missing} EUR short`,
|
|
377
|
+
undefined: () => "Buy",
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
The `-1` of `indexOf` is the same trap. Compared, as here, it is right and the checker is
|
|
383
|
+
silent; used as a position (`splice`, `slice`, an index) before the comparison it is reported
|
|
384
|
+
([below](#a-not-found-answer-used-as-a-value)). Either way an `Option` says it in the type:
|
|
385
|
+
|
|
386
|
+
```ts bad
|
|
387
|
+
const SIZES = ["small", "medium", "large"] as const;
|
|
388
|
+
|
|
389
|
+
export function sizeRank(input: string): number {
|
|
390
|
+
return SIZES.findIndex((size) => size === input);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export function isKnownSize(input: string): boolean {
|
|
394
|
+
return sizeRank(input) !== -1;
|
|
395
|
+
}
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
```ts good
|
|
399
|
+
import { indexIn } from "@evobug_com/safe-ts-std/array";
|
|
400
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
401
|
+
|
|
402
|
+
const SIZES = ["small", "medium", "large"] as const;
|
|
403
|
+
|
|
404
|
+
export function sizeRank(input: string): Option<0 | 1 | 2> {
|
|
405
|
+
return indexIn(SIZES, input);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export function isKnownSize(input: string): boolean {
|
|
409
|
+
return sizeRank(input) !== undefined;
|
|
410
|
+
}
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
A sentinel inside a project helper's contract (a callback that returns `''` to mean "use the
|
|
414
|
+
default") is the same thing: change the contract to `Option<string>`, and drop the sentence
|
|
415
|
+
that describes the `''` from the project's conventions.
|
|
416
|
+
|
|
417
|
+
## A closed set of states
|
|
418
|
+
|
|
419
|
+
A value that is one of a few kinds, handled with `if`/`else if` on strings, compiles when a
|
|
420
|
+
kind is added and every chain misses it: the new kind takes the last `else`.
|
|
421
|
+
`exhaustive-dispatch` reports a chain that tests two kinds or more and leaves some to that
|
|
422
|
+
`else` (on an `Enum`'s tag, a union of literals, or the constants of a code object), and
|
|
423
|
+
`exhaustive-switch` a `switch` on one without `default: unreachable(x)`. An `Enum` with `match`
|
|
424
|
+
stops compiling instead. Each variant carries only its own data. For a union already
|
|
425
|
+
discriminated by a `type` field, `safe-ts migrate union-to-enum <Type> <dir>` converts it with
|
|
426
|
+
its producers and consumers: checks become `is`, a `switch` whose every case returns becomes
|
|
427
|
+
`match`.
|
|
428
|
+
|
|
429
|
+
```ts bad exhaustive-dispatch
|
|
430
|
+
export type Payment = {
|
|
431
|
+
readonly kind: "card" | "transfer" | "cash";
|
|
432
|
+
readonly last4?: string;
|
|
433
|
+
readonly iban?: string;
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
export function paymentLabel(payment: Payment): string {
|
|
437
|
+
if (payment.kind === "card") return `Card ending ${payment.last4 ?? "????"}`;
|
|
438
|
+
if (payment.kind === "transfer") return `Transfer from ${payment.iban ?? "unknown"}`;
|
|
439
|
+
return "Cash";
|
|
440
|
+
}
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
```ts good
|
|
444
|
+
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
445
|
+
|
|
446
|
+
export type Payment = Enum<{
|
|
447
|
+
Card: { last4: string };
|
|
448
|
+
Transfer: { iban: string };
|
|
449
|
+
Cash: {};
|
|
450
|
+
}>;
|
|
451
|
+
export const Payment = constructors<Payment>();
|
|
452
|
+
|
|
453
|
+
export function paymentLabel(payment: Payment): string {
|
|
454
|
+
return match(payment, {
|
|
455
|
+
Card: ({ last4 }) => `Card ending ${last4}`,
|
|
456
|
+
Transfer: ({ iban }) => `Transfer from ${iban}`,
|
|
457
|
+
Cash: () => "Cash",
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
Plain names with no data (`"asc" | "desc"`) can stay a union of strings, handled with
|
|
463
|
+
`match(order, { asc: ..., desc: ... })` like an enum; the `Enum` pays off when the kinds carry
|
|
464
|
+
different data. A union or a code object of numbers (`Object.freeze({ WALK: 0, RUN: 1 })`, a `codesOf(...)` table) that stays
|
|
465
|
+
one is handled in a `switch` ending in `default: return unreachable(x)`, or read from a table
|
|
466
|
+
typed by the set (`Record<Phase, number>`), which TypeScript checks for every member. Type the
|
|
467
|
+
field as the set (`phase: Phase`, with `type Phase = (typeof Phase)[keyof typeof Phase]`), not
|
|
468
|
+
`number`.
|
|
469
|
+
|
|
470
|
+
```ts good
|
|
471
|
+
import { unreachable } from "@evobug_com/safe-ts-std/enum";
|
|
472
|
+
|
|
473
|
+
export const Phase = Object.freeze({ WALK: 0, RUN: 1, TEND: 2 });
|
|
474
|
+
export type Phase = (typeof Phase)[keyof typeof Phase];
|
|
475
|
+
|
|
476
|
+
const CARRY: Readonly<Record<Phase, number>> = { [Phase.WALK]: 10, [Phase.RUN]: 5, [Phase.TEND]: 0 };
|
|
477
|
+
|
|
478
|
+
export function carryMax(phase: Phase): number {
|
|
479
|
+
return CARRY[phase];
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export function phaseName(phase: Phase): string {
|
|
483
|
+
switch (phase) {
|
|
484
|
+
case Phase.WALK:
|
|
485
|
+
return "walk";
|
|
486
|
+
case Phase.RUN:
|
|
487
|
+
return "run";
|
|
488
|
+
case Phase.TEND:
|
|
489
|
+
return "tend";
|
|
490
|
+
default:
|
|
491
|
+
return unreachable(phase);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
A plain `string` compared with many words (a command, a mode read from the URL) is a set that
|
|
497
|
+
exists only as those tests, and its other lists (a help text, a menu) drift. Parse it once at
|
|
498
|
+
the boundary into a union, with a table that maps the words (aliases included) to the members,
|
|
499
|
+
and `match` on the union. `string-dispatch` (idiomatic) reports the comparisons; a function
|
|
500
|
+
declared to return the closed type is the parser and isn't reported.
|
|
501
|
+
|
|
502
|
+
Three other tests leave a new member to chance, and the fix is always to name the members once:
|
|
503
|
+
|
|
504
|
+
- `u.phase === Phase.INSIDE && u.job !== Job.FLEE` guarding work is work for "every job but
|
|
505
|
+
`FLEE`", and a job added later takes it (`negative-member-guard`). Test a named set instead.
|
|
506
|
+
An early `return;` / `continue` for the excluded member is fine.
|
|
507
|
+
- `afterJob >= Job.MOVE && afterJob <= Job.IGNITE` picks members by code, and a code table's new
|
|
508
|
+
names are appended past the range (`code-range-compare`). Name the members; where the order is
|
|
509
|
+
the meaning (stages, levels), put `@ordered` in the doc comment of the table's `const`.
|
|
510
|
+
- The same value tested against overlapping sets in several functions (a check, a reader, a
|
|
511
|
+
writer) is copies of one set that drift (`inline-member-set`, from `safe-ts check`). Export one
|
|
512
|
+
set and use it in all of them.
|
|
513
|
+
|
|
514
|
+
```ts good
|
|
515
|
+
export const Job = Object.freeze({ NONE: 0, MOVE: 1, DEPOSIT: 2, FLEE: 3, MINE: 4, WORSHIP: 5 });
|
|
516
|
+
export type Job = (typeof Job)[keyof typeof Job];
|
|
517
|
+
|
|
518
|
+
/** Jobs a unit away from them keeps: the checks, the save writer and the reader use this set. */
|
|
519
|
+
export const KEPT_JOBS: ReadonlySet<Job> = new Set([Job.MOVE, Job.DEPOSIT, Job.MINE]);
|
|
520
|
+
|
|
521
|
+
export function keptResume(afterJob: Job): boolean {
|
|
522
|
+
return KEPT_JOBS.has(afterJob);
|
|
523
|
+
}
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
## A set of boolean flags
|
|
527
|
+
|
|
528
|
+
`isOpen`, `isSaving` and `hasFailed` side by side allow combinations that make no sense (saving
|
|
529
|
+
and failed at once) and need every reader to know which wins. When at most one can be true,
|
|
530
|
+
they are one value.
|
|
531
|
+
|
|
532
|
+
```ts bad
|
|
533
|
+
export type Dialog = {
|
|
534
|
+
readonly isOpen: boolean;
|
|
535
|
+
readonly isSaving: boolean;
|
|
536
|
+
readonly failure: string;
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
export function dialogTitle(dialog: Dialog): string {
|
|
540
|
+
if (!dialog.isOpen) return "";
|
|
541
|
+
if (dialog.isSaving) return "Saving…";
|
|
542
|
+
return dialog.failure === "" ? "Edit" : `Failed: ${dialog.failure}`;
|
|
543
|
+
}
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
```ts good
|
|
547
|
+
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
548
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
549
|
+
|
|
550
|
+
export type Dialog = Enum<{
|
|
551
|
+
Closed: {};
|
|
552
|
+
Editing: {};
|
|
553
|
+
Saving: {};
|
|
554
|
+
Failed: { reason: string };
|
|
555
|
+
}>;
|
|
556
|
+
export const Dialog = constructors<Dialog>();
|
|
557
|
+
|
|
558
|
+
export function dialogTitle(dialog: Dialog): Option<string> {
|
|
559
|
+
return match(dialog, {
|
|
560
|
+
Closed: () => undefined,
|
|
561
|
+
Editing: () => "Edit",
|
|
562
|
+
Saving: () => "Saving…",
|
|
563
|
+
Failed: ({ reason }) => `Failed: ${reason}`,
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
When the flags describe async work (loading, failed, loaded), the value is `AsyncState`, kept
|
|
569
|
+
by `useTask`: see the trio entry of the framework catalogue.
|
|
570
|
+
|
|
571
|
+
## Reading an enum: one style
|
|
572
|
+
|
|
573
|
+
Both `x.tag === "Ready"` and `is(x, ...)` / `variant(...)` / `match` compile and narrow. The
|
|
574
|
+
SAFE-TS style is the second, and with the idiomatic layer on, `prefer-is-over-tag` reports the
|
|
575
|
+
raw tag (`x.tag === "..."`, `x.tag !== "..."`, `switch (x.tag)`) in code and in Vue templates,
|
|
576
|
+
with a quick fix to `is(x, "Ready")`, or `is(x, Status.Ready)` where the enum's constructors
|
|
577
|
+
are in scope (`safe-ts fix prefer-is-over-tag src/` for all of them; with the prelude on it
|
|
578
|
+
adds no import). Write the style in the project's conventions:
|
|
579
|
+
|
|
580
|
+
- `match(value, { ... })` when every variant needs its own decision: a variant added later
|
|
581
|
+
makes it stop compiling.
|
|
582
|
+
- `is(value, Type.Variant)` for "is it this one?", `variant(value, Type.Variant)?.field` to
|
|
583
|
+
read one variant's data, and `_` in `match` for "everything else". Generic enums take the
|
|
584
|
+
constructor too: `is(state, AsyncState.Ready)`, `variant(state, AsyncState.Ready)?.value`.
|
|
585
|
+
- In Vue templates, `<Match :value="state">` with a slot per variant (vue-tsc accepts it; the
|
|
586
|
+
older `:on` fails vue-tsc), or a `v-if` chain of `is(state, AsyncState.Ready)`, which
|
|
587
|
+
`vue-exhaustive-v-if` checks like one on `.tag`; in JSX, `<Match on={state} ... />`.
|
|
588
|
+
|
|
589
|
+
```ts bad prefer-is-over-tag
|
|
590
|
+
import type { Enum } from "@evobug_com/safe-ts-std/enum";
|
|
591
|
+
|
|
592
|
+
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
|
|
593
|
+
|
|
594
|
+
export function publishedAt(status: Status): string {
|
|
595
|
+
return status.tag === "Published" ? status.at : "not published";
|
|
596
|
+
}
|
|
597
|
+
```
|
|
598
|
+
|
|
599
|
+
```ts good
|
|
600
|
+
import { constructors, type Enum, variant } from "@evobug_com/safe-ts-std/enum";
|
|
601
|
+
|
|
602
|
+
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
|
|
603
|
+
const Status = constructors<Status>();
|
|
604
|
+
|
|
605
|
+
export function publishedAt(status: Status): string {
|
|
606
|
+
return variant(status, Status.Published)?.at ?? "not published";
|
|
607
|
+
}
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
The build turns `is` and `variant` on a plain variable into the same tag check, so the style
|
|
611
|
+
costs nothing at runtime (guide: Enums and match). Name the variant by its constructor when the
|
|
612
|
+
enum has one: `is(x, "Published")` is the same test, and `prefer-constructor-tag` (idiomatic)
|
|
613
|
+
reports it with a quick fix to `Status.Published`, so a rename follows every use. An enum
|
|
614
|
+
without constructors keeps the string form. Keep tags strings: an interned string tag reads as
|
|
615
|
+
fast as a number (guide: Performance myths).
|
|
616
|
+
|
|
617
|
+
## A union told apart by keys
|
|
618
|
+
|
|
619
|
+
`'issueId' in choice` narrows in TypeScript, but the union has no name for its kinds and any
|
|
620
|
+
object with that key fits. Give each kind a tag. With the idiomatic layer on,
|
|
621
|
+
`key-presence-union` reports `"key" in x` that tells apart the members of a union declared in
|
|
622
|
+
the project.
|
|
623
|
+
|
|
624
|
+
```ts bad key-presence-union
|
|
625
|
+
type ByIssue = { readonly issueId: number };
|
|
626
|
+
type ByBranch = { readonly branch: string };
|
|
627
|
+
export type Target = ByIssue | ByBranch;
|
|
628
|
+
|
|
629
|
+
export function targetLabel(target: Target): string {
|
|
630
|
+
return "issueId" in target ? `#${target.issueId}` : target.branch;
|
|
631
|
+
}
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
```ts good
|
|
635
|
+
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
636
|
+
|
|
637
|
+
export type Target = Enum<{ Issue: { issueId: number }; Branch: { branch: string } }>;
|
|
638
|
+
export const Target = constructors<Target>();
|
|
639
|
+
|
|
640
|
+
export function targetLabel(target: Target): string {
|
|
641
|
+
return match(target, {
|
|
642
|
+
Issue: ({ issueId }) => `#${issueId}`,
|
|
643
|
+
Branch: ({ branch }) => branch,
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
```
|
|
647
|
+
|
|
648
|
+
Keep `in` for objects from outside whose shape you are finding out (and prefer `validate<T>`
|
|
649
|
+
for those).
|
|
650
|
+
|
|
651
|
+
## An API that sends null
|
|
652
|
+
|
|
653
|
+
The server sends `null` for "none". Convert it where the data comes in, so the rest of the
|
|
654
|
+
code sees `undefined`: `validate<T>` and `parseJson<T>` turn a JSON `null` into `undefined` for
|
|
655
|
+
`Option<T>` and optional fields. On the way out, `JSON.stringify` leaves `undefined` fields
|
|
656
|
+
out, so a field that was sent as `null` disappears from the body. A body that changes a record
|
|
657
|
+
(`PATCH`) is a `Patch<T>` from `@evobug_com/safe-ts-std/patch`: each field left out (or `keep`),
|
|
658
|
+
cleared (`clear`, sent as `null`) or set, one spelling each (guide: Absence, "Sending \"clear
|
|
659
|
+
this field\""; Proof types, "Patch<T>"). Another explicit `null` the protocol needs is
|
|
660
|
+
`jsonNull` (JSON guide, "Keeping a JSON null").
|
|
661
|
+
|
|
662
|
+
```ts bad no-null no-unchecked-cast unhandled-failure
|
|
663
|
+
export type Issue = { readonly id: number; readonly dueDate: string | null };
|
|
664
|
+
|
|
665
|
+
export function readIssue(text: string): Issue {
|
|
666
|
+
return JSON.parse(text) as Issue;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
export function clearDueDate(issue: Issue): string {
|
|
670
|
+
return JSON.stringify({ id: issue.id, dueDate: null });
|
|
671
|
+
}
|
|
672
|
+
```
|
|
673
|
+
|
|
674
|
+
```ts good
|
|
675
|
+
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
|
|
676
|
+
import { clear, type Patch } from "@evobug_com/safe-ts-std/patch";
|
|
677
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
678
|
+
|
|
679
|
+
export type Issue = { readonly id: number; readonly dueDate: Option<string> };
|
|
680
|
+
|
|
681
|
+
export function readIssue(text: string): JsonResult<Issue> {
|
|
682
|
+
return parseJson<Issue>(text);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** The server clears a field it receives as `null`; a missing key leaves it as it is. */
|
|
686
|
+
export function clearDueDate(issue: Issue): string {
|
|
687
|
+
const body: Patch<Issue> = { id: issue.id, dueDate: clear };
|
|
688
|
+
return JSON.stringify(body);
|
|
689
|
+
}
|
|
690
|
+
```
|
|
691
|
+
|
|
692
|
+
- In a `Patch<T>`, `undefined` never clears a field, and only a field that may be missing can be
|
|
693
|
+
cleared (`{ id: clear }` doesn't compile). `JSON.stringify` of it isn't reported: the object
|
|
694
|
+
is its own wire form.
|
|
695
|
+
- `jsonNull`, `JsonNull` and `clear` belong to data that goes out (a request body) or a type the
|
|
696
|
+
protocol defines that way. Inside the app, "asked and there is none" is an `Option` (or an
|
|
697
|
+
`Enum` variant when it must differ from "not loaded"), never `Option<T | JsonNull>`.
|
|
698
|
+
- A transport adapter that rewrites every `undefined` into `null` on the way out (and back on
|
|
699
|
+
the way in) is a bridge, not the target: it gives the code two spellings of "clear", and a
|
|
700
|
+
stray `undefined` clears data on the server. If the plan uses one, the architecture
|
|
701
|
+
document says so and says when it goes.
|
|
702
|
+
- Before changing what a body sends, record what it sends today (see
|
|
703
|
+
[behaviour.md](behaviour.md)): a key that was `null` and is now missing is a different
|
|
704
|
+
request for a server that tells them apart.
|
|
705
|
+
|
|
706
|
+
## JSON and storage
|
|
707
|
+
|
|
708
|
+
`JSON.parse(text) as T` believes the text. `parseJson<T>` checks it and returns a `Result`.
|
|
709
|
+
`unsafe(() => JSON.parse(text))` gives `unknown` (std turns a function's `any` into `unknown`),
|
|
710
|
+
and with std's strict-lib in tsconfig.json `"types"` so does `JSON.parse` itself: either way
|
|
711
|
+
the value goes through `validate<T>` before use. A message event is the same:
|
|
712
|
+
`MessageEvent<unknown>`, never a bare `MessageEvent`, whose `data` is `any`, nor
|
|
713
|
+
`MessageEvent<Job>`, which claims what was posted (`no-hidden-any`). A worker thread's
|
|
714
|
+
`workerData` and `"message"` value are the same: `validate<T>` them where they come in.
|
|
715
|
+
With the browser pack, `getItem(localStorage, key)` returns an `Option<string>` and
|
|
716
|
+
`setItem(...)` a `Result` (a full storage is a value to check).
|
|
717
|
+
|
|
718
|
+
```ts bad unhandled-failure no-unchecked-cast no-null
|
|
719
|
+
type Draft = { readonly title: string; readonly body: string };
|
|
720
|
+
|
|
721
|
+
export function loadDraft(): Draft | null {
|
|
722
|
+
const text = localStorage.getItem("draft");
|
|
723
|
+
return text === null ? null : (JSON.parse(text) as Draft);
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
export function saveDraft(draft: Draft): void {
|
|
727
|
+
localStorage.setItem("draft", JSON.stringify(draft));
|
|
728
|
+
}
|
|
729
|
+
```
|
|
730
|
+
|
|
731
|
+
```ts good
|
|
732
|
+
import { getItem, setItem } from "@evobug_com/safe-ts-feature-browser/storage";
|
|
733
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
734
|
+
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
|
|
735
|
+
import { mapErr, type Option, type Result } from "@evobug_com/safe-ts-std/result";
|
|
736
|
+
|
|
737
|
+
type Draft = { readonly title: string; readonly body: string };
|
|
738
|
+
|
|
739
|
+
export type SaveError = Enum<{ StorageFull: {} }>;
|
|
740
|
+
export const SaveError = constructors<SaveError>();
|
|
741
|
+
|
|
742
|
+
/** No saved draft is `undefined`; a saved one that doesn't fit `Draft` is an error. */
|
|
743
|
+
export function loadDraft(): JsonResult<Option<Draft>> {
|
|
744
|
+
const text = getItem(localStorage, "draft");
|
|
745
|
+
return text === undefined ? undefined : parseJson<Draft>(text);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
export function saveDraft(draft: Draft): Result<void, SaveError> {
|
|
749
|
+
return mapErr(setItem(localStorage, "draft", JSON.stringify(draft)), () => SaveError.StorageFull());
|
|
750
|
+
}
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
Read with `validate`, but write back the raw object when another owner keeps fields of its own
|
|
754
|
+
in the same place (`history.state`): `validate<T>` drops the keys `T` doesn't list.
|
|
755
|
+
|
|
756
|
+
## A cast
|
|
757
|
+
|
|
758
|
+
`as T` on data from outside is a guess; on a literal it is usually a missing annotation; `!`
|
|
759
|
+
on an index or a lookup hides the case the type warns about. Each has a better form, and none
|
|
760
|
+
of them is a new `as`.
|
|
761
|
+
|
|
762
|
+
- Outside data: `validate<T>(value)` / `parseJson<T>(text)`.
|
|
763
|
+
- A literal that should have a type: annotate the variable (`const x: T = ...`) or use
|
|
764
|
+
`satisfies T`.
|
|
765
|
+
- A DOM element: the browser pack's `querySelector(form, "[name=email]", HTMLInputElement)`,
|
|
766
|
+
checked with `instanceof` and typed by the class (`undefined` when missing or of another
|
|
767
|
+
class), or in Vue `useElement` (see the Vue catalogue).
|
|
768
|
+
- A value no check fits, that another part of the same program made (a worker's message):
|
|
769
|
+
`trust<T>(value)`, with a reason comment ([A trusted boundary](#a-trusted-boundary)).
|
|
770
|
+
- A brand (`Html`, `SafeUrl`, `RegexSource`, `Ascii`): only its constructors make one
|
|
771
|
+
(`escapeHtml` or a sanitizer declared with `defineSanitizer`, `safeHref` / `safeUrl`,
|
|
772
|
+
`escapeRegExp`, `isAscii` / `asciiOf`). `as Html` is `brand-constructor`, an error (guide:
|
|
773
|
+
Proof types).
|
|
774
|
+
- `items[i]!`: see [An index read](#an-index-read).
|
|
775
|
+
- A library's loose type: the patterns in the guide's "Typing without casts" page (module
|
|
776
|
+
augmentation, a precise signature over a loose implementation).
|
|
777
|
+
|
|
778
|
+
```ts bad no-unchecked-cast
|
|
779
|
+
type Settings = { readonly theme: "light" | "dark"; readonly fontSize: number };
|
|
780
|
+
|
|
781
|
+
export function readSettings(message: MessageEvent<unknown>): Settings {
|
|
782
|
+
return message.data as Settings;
|
|
783
|
+
}
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
```ts good
|
|
787
|
+
import { type JsonResult, validate } from "@evobug_com/safe-ts-std/json";
|
|
788
|
+
|
|
789
|
+
type Settings = { readonly theme: "light" | "dark"; readonly fontSize: number };
|
|
790
|
+
|
|
791
|
+
export function readSettings(message: MessageEvent<unknown>): JsonResult<Settings> {
|
|
792
|
+
return validate<Settings>(message.data);
|
|
793
|
+
}
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
`validate<T>` takes types declared in the project: imported by name (relatively or through a
|
|
797
|
+
tsconfig `paths` alias), and namespace members such as a generated `Backend.Models.User`, also
|
|
798
|
+
global ones from a declaration file. Not package types, global types from `@types/...` or
|
|
799
|
+
`declare module "..."` blocks ([tool-gaps.md](tool-gaps.md#rules-and-the-checker)).
|
|
800
|
+
|
|
801
|
+
## A hand-written type guard
|
|
802
|
+
|
|
803
|
+
`value is T`, `asserts value is T` and an overload over a looser implementation are casts:
|
|
804
|
+
TypeScript never checks the body against them (`return true` compiles), so `no-type-predicate`
|
|
805
|
+
and `no-overload` report them, as errors. For data of unknown shape, use `validate<T>`, which
|
|
806
|
+
tests every field:
|
|
807
|
+
|
|
808
|
+
```ts bad no-type-predicate
|
|
809
|
+
type User = { readonly id: number; readonly name: string; readonly email: string };
|
|
810
|
+
|
|
811
|
+
export function isUser(value: unknown): value is User {
|
|
812
|
+
return typeof value === "object" && value !== null && "id" in value;
|
|
813
|
+
}
|
|
814
|
+
```
|
|
815
|
+
|
|
816
|
+
```ts good
|
|
817
|
+
import { type JsonResult, validate } from "@evobug_com/safe-ts-std/json";
|
|
818
|
+
|
|
819
|
+
type User = { readonly id: number; readonly name: string; readonly email: string };
|
|
820
|
+
|
|
821
|
+
export function readUser(value: unknown): JsonResult<User> {
|
|
822
|
+
return validate<User>(value);
|
|
823
|
+
}
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
Everything else, by what the guard did:
|
|
827
|
+
|
|
828
|
+
- **Its body is one test TypeScript narrows by** (`typeof`, `instanceof`, `Array.isArray`,
|
|
829
|
+
`x !== undefined`, `!!x`, a discriminant, `is(x, Variant)`, `isSome(x)`): drop `: x is T`
|
|
830
|
+
(`safe-ts fix no-type-predicate --fix "Let TypeScript infer"`). TypeScript infers the same
|
|
831
|
+
predicate and checks it. When that stops the code compiling, the claim was more than the
|
|
832
|
+
test: fix what the error points at, not the inference.
|
|
833
|
+
- **A filter**: `.filter(isSome)`, `.filter((e) => is(e, "Moved"))`; a second condition goes in a
|
|
834
|
+
second `.filter` once the first narrowed.
|
|
835
|
+
- **One of a list** (`KINDS.some((k) => k === name)`): `KINDS.find((k) => k === name)`, an
|
|
836
|
+
`Option<Kind>`; a table's key: `getOwn(TABLE, name)`.
|
|
837
|
+
- **`Record<string, unknown>`**: std's `isJsonObject` / `isJsonPlainObject`.
|
|
838
|
+
- **An assertion**: return the check's `Result`, or `if (!test) panic("...")` at the use site.
|
|
839
|
+
`asserts ok` whose body is exactly `if (!ok) throw ...` / `panic(...)` is allowed.
|
|
840
|
+
- **A method on a library's object** (`"activateVao" in proto`), a result type the body can't
|
|
841
|
+
build: `trust<T>(value)` next to the test, with the reason (see "A trusted boundary").
|
|
842
|
+
- **Overloads** whose results differ: one function per signature, or one signature returning
|
|
843
|
+
an `Enum`. Overloads with the implementation's own result, each parameter one member of its
|
|
844
|
+
union, are allowed.
|
|
845
|
+
|
|
846
|
+
## An index read
|
|
847
|
+
|
|
848
|
+
With `noUncheckedIndexedAccess`, `items[i]` is `T | undefined`. Give the missing case a value,
|
|
849
|
+
or let the checker see the bound: `items[i]!` inside `for (let i = 0; i < items.length; i++)`
|
|
850
|
+
is accepted (rule page `no-unchecked-cast` lists the shapes).
|
|
851
|
+
|
|
852
|
+
```ts bad no-unchecked-cast
|
|
853
|
+
export function firstWord(text: string): string {
|
|
854
|
+
return text.split(" ")[0]!;
|
|
855
|
+
}
|
|
856
|
+
```
|
|
857
|
+
|
|
858
|
+
```ts good
|
|
859
|
+
export function firstWord(text: string): string {
|
|
860
|
+
const [first] = text.split(" ");
|
|
861
|
+
return first ?? "";
|
|
862
|
+
}
|
|
863
|
+
```
|
|
864
|
+
|
|
865
|
+
Turn both flags (`noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`) on at the start, not
|
|
866
|
+
at the end: their errors show up in the code each builder touches, instead of all at once after
|
|
867
|
+
the merge, and a type-aware oxlint stops calling the `!` unnecessary.
|
|
868
|
+
|
|
869
|
+
## An optional key
|
|
870
|
+
|
|
871
|
+
Under `exactOptionalPropertyTypes`, `key?: T` refuses an explicit `undefined`, so
|
|
872
|
+
`{ id, delivery: x === "pickup" ? undefined : x }` stops compiling. Leave the key out. The
|
|
873
|
+
recommended form is a conditional spread of a one-key literal,
|
|
874
|
+
`...(x === undefined ? {} : { x })`, also inside a nested object or an argument (guide:
|
|
875
|
+
Absence, "Dropping an optional key"):
|
|
876
|
+
|
|
877
|
+
```ts good
|
|
878
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
879
|
+
|
|
880
|
+
type Callbacks = { readonly onAccept?: () => void; readonly onCancel?: () => void };
|
|
881
|
+
|
|
882
|
+
declare function openDialog(options: { readonly title: string; readonly callbacks: Callbacks }): void;
|
|
883
|
+
|
|
884
|
+
export function confirm(title: string, onAccept: Option<() => void>, onCancel: Option<() => void>): void {
|
|
885
|
+
openDialog({
|
|
886
|
+
title,
|
|
887
|
+
callbacks: {
|
|
888
|
+
...(onAccept === undefined ? {} : { onAccept }),
|
|
889
|
+
...(onCancel === undefined ? {} : { onCancel }),
|
|
890
|
+
},
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
- `stable-shape` accepts one such spread in any literal, and two where the type the literal is
|
|
896
|
+
written for declares both keys optional. With three or more (eight shapes), and for objects
|
|
897
|
+
read in a hot loop, declare the fields `Option<T>` and always write them, `x: undefined`
|
|
898
|
+
included; assigning them after the literal (`o.x = v`) makes as many shapes. The same for a Vue component's optional props a template always passes
|
|
899
|
+
(`:x="maybe"`): declare them `x?: Option<T>`.
|
|
900
|
+
- To drop keys from an existing object, `omit(settings, "theme")` (`@evobug_com/safe-ts-std/dict`),
|
|
901
|
+
not `delete` or `{ ...settings, theme: undefined }`.
|
|
902
|
+
- Two object literals, one without the key, are fine too when the branches differ anyway:
|
|
903
|
+
|
|
904
|
+
```ts good
|
|
905
|
+
type Delivery = "pickup" | "courier" | "post";
|
|
906
|
+
|
|
907
|
+
export type Order = { readonly id: string; readonly delivery?: Exclude<Delivery, "pickup"> };
|
|
908
|
+
|
|
909
|
+
export function order(id: string, delivery: Delivery): Order {
|
|
910
|
+
return delivery === "pickup" ? { id } : { id, delivery };
|
|
911
|
+
}
|
|
912
|
+
```
|
|
913
|
+
|
|
914
|
+
Decide the form for the component library's optional props in the foundation step, once
|
|
915
|
+
([order-and-gates.md](order-and-gates.md)).
|
|
916
|
+
|
|
917
|
+
With the idiomatic rules on, `no-optional-field` reports `key?:` in the project's own types
|
|
918
|
+
(not JSON types, props, a library's options or declarations): a value whose type doesn't list
|
|
919
|
+
the key is assignable there, holding whatever it had. Declare the field `key: Option<T>` and
|
|
920
|
+
write the key where the object is made (`key: undefined` when there is none). `?:` stays for
|
|
921
|
+
the shapes above, like `Callbacks` when `openDialog` is a library's.
|
|
922
|
+
|
|
923
|
+
## A method in an interface
|
|
924
|
+
|
|
925
|
+
`handle(animal: Animal): string` in an interface or type literal is checked in both directions,
|
|
926
|
+
so an implementation that only takes a `Dog` is accepted (`no-method-signature`). Write the
|
|
927
|
+
member as a property; `safe-ts fix no-method-signature <dirs> --write` rewrites them all, and
|
|
928
|
+
`tsc` then shows each assignment that relied on the bivariance.
|
|
929
|
+
|
|
930
|
+
```ts bad no-method-signature
|
|
931
|
+
type Animal = { readonly kind: string };
|
|
932
|
+
|
|
933
|
+
export interface Handler {
|
|
934
|
+
handle(animal: Animal): string;
|
|
935
|
+
}
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
```ts good
|
|
939
|
+
type Animal = { readonly kind: string };
|
|
940
|
+
|
|
941
|
+
export interface Handler {
|
|
942
|
+
readonly handle: (animal: Animal) => string;
|
|
943
|
+
}
|
|
944
|
+
```
|
|
945
|
+
|
|
946
|
+
## An override that asks for more
|
|
947
|
+
|
|
948
|
+
A class's own methods are compared both ways too: `override admit(dog: Dog)` over
|
|
949
|
+
`admit(animal: Animal)` compiles, and a call through the base class hands it any animal
|
|
950
|
+
(`override-parameter`). Take the base's parameter type and check inside, or declare the member
|
|
951
|
+
on the base as a function-typed property (`readonly admit = (animal: Animal): string => ...`),
|
|
952
|
+
which TypeScript checks in every override.
|
|
953
|
+
|
|
954
|
+
```ts bad override-parameter
|
|
955
|
+
type Animal = { readonly kind: string };
|
|
956
|
+
type Dog = { readonly kind: string; readonly bark: () => string };
|
|
957
|
+
|
|
958
|
+
export class Shelter {
|
|
959
|
+
admit(animal: Animal): string {
|
|
960
|
+
return animal.kind;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
export class Kennel extends Shelter {
|
|
965
|
+
override admit(dog: Dog): string {
|
|
966
|
+
return dog.bark();
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
```ts good
|
|
972
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
973
|
+
|
|
974
|
+
type Animal = { readonly kind: string; readonly bark: Option<() => string> };
|
|
975
|
+
|
|
976
|
+
export class Shelter {
|
|
977
|
+
admit(animal: Animal): string {
|
|
978
|
+
return animal.kind;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
export class Kennel extends Shelter {
|
|
983
|
+
override admit(animal: Animal): string {
|
|
984
|
+
return animal.bark === undefined ? "only dogs here" : animal.bark();
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
## A failure behind an interface
|
|
990
|
+
|
|
991
|
+
A call through an interface, an abstract method or a stored callback runs whatever was put
|
|
992
|
+
there, so the checker can't follow it: the type must say what it can fail with
|
|
993
|
+
(`failure-contract`). A function type that says nothing can't fail, so an implementation that
|
|
994
|
+
throws a `PropagateError` is reported where it is put in. Decide where the failure belongs:
|
|
995
|
+
handle it inside the implementation (the slot stays one that can't fail), or declare it on the
|
|
996
|
+
slot with `Throws<R, E>` and handle it at the callers, which the checker then holds to it. For
|
|
997
|
+
an `async` member, `Promise<Throws<T, E>>`; for a callback kept in a field or a list,
|
|
998
|
+
`Throwing<Args, R, E>`.
|
|
999
|
+
|
|
1000
|
+
```ts bad failure-contract
|
|
1001
|
+
import { PropagateError } from "@evobug_com/safe-ts-std/result";
|
|
1002
|
+
|
|
1003
|
+
export class Offline extends PropagateError {}
|
|
1004
|
+
|
|
1005
|
+
export interface Feed {
|
|
1006
|
+
readonly latest: () => string;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
export const remoteFeed: Feed = {
|
|
1010
|
+
latest: () => {
|
|
1011
|
+
throw new Offline("no network");
|
|
1012
|
+
},
|
|
1013
|
+
};
|
|
1014
|
+
```
|
|
1015
|
+
|
|
1016
|
+
```ts good
|
|
1017
|
+
import { PropagateError, type Throws } from "@evobug_com/safe-ts-std/result";
|
|
1018
|
+
|
|
1019
|
+
export class Offline extends PropagateError {}
|
|
1020
|
+
|
|
1021
|
+
export interface Feed {
|
|
1022
|
+
readonly latest: () => Throws<string, Offline>;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
export const remoteFeed: Feed = {
|
|
1026
|
+
latest: () => {
|
|
1027
|
+
throw new Offline("no network");
|
|
1028
|
+
},
|
|
1029
|
+
};
|
|
1030
|
+
```
|
|
1031
|
+
|
|
1032
|
+
On an existing codebase, `safe-ts check` lists each implementation that fails under a slot
|
|
1033
|
+
that declares nothing: one finding per member, so the census shows which interfaces need a
|
|
1034
|
+
declaration. Declaring it moves the finding to the callers that don't handle it.
|
|
1035
|
+
|
|
1036
|
+
## A method the language calls for you
|
|
1037
|
+
|
|
1038
|
+
`toString`, `valueOf`, `toJSON`, `[Symbol.iterator]`, `then`, `[Symbol.dispose]` run without a
|
|
1039
|
+
call naming them (a template, `a < b`, `JSON.stringify`, `for...of`, `await`, `using`), so a
|
|
1040
|
+
`PropagateError` they let out reaches nobody who was told (`implicit-propagation`). Keep them
|
|
1041
|
+
total and put what can fail in a method the caller names; an iteration that may fail becomes a
|
|
1042
|
+
generator method (`for (const row of table.rows())`), which is followed where it is stepped.
|
|
1043
|
+
|
|
1044
|
+
```ts bad implicit-propagation
|
|
1045
|
+
import { PropagateError } from "@evobug_com/safe-ts-std/result";
|
|
1046
|
+
|
|
1047
|
+
class Unpriced extends PropagateError {}
|
|
1048
|
+
|
|
1049
|
+
export class Price {
|
|
1050
|
+
readonly cents: number;
|
|
1051
|
+
constructor(cents: number) {
|
|
1052
|
+
this.cents = cents;
|
|
1053
|
+
}
|
|
1054
|
+
toString(): string {
|
|
1055
|
+
if (this.cents < 0) throw new Unpriced("negative");
|
|
1056
|
+
return `${this.cents / 100} EUR`;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
```
|
|
1060
|
+
|
|
1061
|
+
```ts good
|
|
1062
|
+
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
1063
|
+
|
|
1064
|
+
export class Price {
|
|
1065
|
+
readonly cents: number;
|
|
1066
|
+
constructor(cents: number) {
|
|
1067
|
+
this.cents = cents;
|
|
1068
|
+
}
|
|
1069
|
+
format(): Result<string, "negative"> {
|
|
1070
|
+
return this.cents < 0 ? err("negative") : `${this.cents / 100} EUR`;
|
|
1071
|
+
}
|
|
1072
|
+
toString(): string {
|
|
1073
|
+
const text = this.format();
|
|
1074
|
+
return isErr(text) ? "(no price)" : text;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
```
|
|
1078
|
+
|
|
1079
|
+
## A list spread into Math.max or push
|
|
1080
|
+
|
|
1081
|
+
`Math.max(...values)` and `target.push(...extra)` pass every element as an argument: a
|
|
1082
|
+
`RangeError` past about 100,000 elements, and `Math.max()` of nothing is `-Infinity`
|
|
1083
|
+
(`unbounded-spread`). Use `maxOf` / `minOf` (`Option<number>`), a loop for `push`, and a new
|
|
1084
|
+
array (`[...a, ...b]`, which has no limit) for `unshift` and `splice`.
|
|
1085
|
+
|
|
1086
|
+
```ts bad unbounded-spread
|
|
1087
|
+
export function highest(scores: readonly number[]): number {
|
|
1088
|
+
return Math.max(...scores);
|
|
1089
|
+
}
|
|
1090
|
+
```
|
|
1091
|
+
|
|
1092
|
+
```ts good
|
|
1093
|
+
import { maxOf } from "@evobug_com/safe-ts-std/array";
|
|
1094
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
1095
|
+
|
|
1096
|
+
export function highest(scores: readonly number[]): Option<number> {
|
|
1097
|
+
return maxOf(scores);
|
|
1098
|
+
}
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
## A "not found" answer used as a value
|
|
1102
|
+
|
|
1103
|
+
Some built-ins answer "there is none" with a value of their own type, and the code goes on
|
|
1104
|
+
with a wrong one instead of failing: `-1` from `indexOf`, `findIndex` and `search`
|
|
1105
|
+
(`not-found-index`: `splice(-1, 1)` removes the last element), `NaN` from `Date.parse` and
|
|
1106
|
+
from a `new Date(text)` that didn't parse (`number-parse-nan`, as for `Number(text)`), `NaN`
|
|
1107
|
+
from a division by the length of a `filter` that kept nothing (`divide-by-length`), and holes from a write past
|
|
1108
|
+
an array's end, which read as `undefined` under a `number[]` type (`sparse-array-write`). All
|
|
1109
|
+
but the last are warnings. The fix is the check the value needs, before the use, or a type
|
|
1110
|
+
that says "none": `indexIn` (an `Option` index), `Option<number>` for a mean of nothing,
|
|
1111
|
+
a `Map` for a table with gaps.
|
|
1112
|
+
|
|
1113
|
+
```ts bad not-found-index divide-by-length number-parse-nan sparse-array-write
|
|
1114
|
+
import type { Mut } from "@evobug_com/safe-ts-std/mut";
|
|
1115
|
+
|
|
1116
|
+
export function removeTag(tags: Mut<string[]>, tag: string): void {
|
|
1117
|
+
tags.splice(tags.indexOf(tag), 1);
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
export function meanPassTime(runs: readonly { ok: boolean; ms: number }[]): number {
|
|
1121
|
+
const passed = runs.filter((run) => run.ok);
|
|
1122
|
+
return passed.reduce((sum, run) => sum + run.ms, 0) / passed.length;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
export function age(birthday: string, now: Date): number {
|
|
1126
|
+
return now.getFullYear() - new Date(birthday).getFullYear();
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
export function namesByCode(codes: readonly number[]): readonly string[] {
|
|
1130
|
+
const names: string[] = [];
|
|
1131
|
+
for (const code of codes) names[code] = `#${code}`;
|
|
1132
|
+
return names;
|
|
1133
|
+
}
|
|
1134
|
+
```
|
|
1135
|
+
|
|
1136
|
+
```ts good
|
|
1137
|
+
import { indexIn } from "@evobug_com/safe-ts-std/array";
|
|
1138
|
+
import type { Mut } from "@evobug_com/safe-ts-std/mut";
|
|
1139
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
1140
|
+
|
|
1141
|
+
export function removeTag(tags: Mut<string[]>, tag: string): boolean {
|
|
1142
|
+
const at = indexIn(tags, tag);
|
|
1143
|
+
if (at === undefined) return false;
|
|
1144
|
+
tags.splice(at, 1);
|
|
1145
|
+
return true;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
export function meanPassTime(runs: readonly { ok: boolean; ms: number }[]): Option<number> {
|
|
1149
|
+
const passed = runs.filter((run) => run.ok);
|
|
1150
|
+
if (passed.length === 0) return undefined;
|
|
1151
|
+
return passed.reduce((sum, run) => sum + run.ms, 0) / passed.length;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
export function age(birthday: string, now: Date): Option<number> {
|
|
1155
|
+
const born = new Date(birthday);
|
|
1156
|
+
if (Number.isNaN(born.getTime())) return undefined;
|
|
1157
|
+
return now.getFullYear() - born.getFullYear();
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
export function namesByCode(codes: readonly number[]): ReadonlyMap<number, string> {
|
|
1161
|
+
const names = new Map<number, string>();
|
|
1162
|
+
for (const code of codes) names.set(code, `#${code}`);
|
|
1163
|
+
return names;
|
|
1164
|
+
}
|
|
1165
|
+
```
|
|
1166
|
+
|
|
1167
|
+
The idioms that are right because of the `-1` aren't reported:
|
|
1168
|
+
`path.slice(path.lastIndexOf("/") + 1)` (everything after the last slash, or all of it) and
|
|
1169
|
+
`list.splice(list.findLastIndex(...) + 1, 0, item)` (insert after, or at the start). Most of
|
|
1170
|
+
what an existing codebase gets is `list.splice(list.indexOf(x), 1)` where `x` is known to be in
|
|
1171
|
+
the list for a reason the checker can't see: keep the check anyway (`if (at !== -1)`), since a
|
|
1172
|
+
second removal of the same `x` takes another element.
|
|
1173
|
+
|
|
1174
|
+
|
|
1175
|
+
## A regex with the `g` flag tested again
|
|
1176
|
+
|
|
1177
|
+
`test` and `exec` on a regex with `g` (or `y`) start where its last match ended
|
|
1178
|
+
(`lastIndex`): a field regex tested in a method, a local one tested in a loop over other
|
|
1179
|
+
strings or in a callback, answers `true`, `false`, `true` for strings that all match
|
|
1180
|
+
(`regex-last-index`). `g` is for walking the matches of one string; to test, drop it. To walk
|
|
1181
|
+
matches, `text.matchAll(re)`, which doesn't use `lastIndex`.
|
|
1182
|
+
|
|
1183
|
+
```ts good
|
|
1184
|
+
export function numbered(lines: readonly string[]): number {
|
|
1185
|
+
const digits = /\d+/;
|
|
1186
|
+
return lines.filter((line) => digits.test(line)).length;
|
|
1187
|
+
}
|
|
1188
|
+
```
|
|
1189
|
+
|
|
1190
|
+
## An answer nobody reads
|
|
1191
|
+
|
|
1192
|
+
A call whose only point is its answer, as a statement of its own, drops all it did:
|
|
1193
|
+
`name.trim();` leaves `name` untrimmed, `list.concat(more);` and `scores.toSorted(...)` make
|
|
1194
|
+
copies nobody keeps, a function of the program that changes nothing outside itself answers into
|
|
1195
|
+
the void (`unused-answer`, an error). Keep the answer, or assign it where it was meant to go. A
|
|
1196
|
+
member that does something and answers how much of it happened is the same rule:
|
|
1197
|
+
`encoder.encodeInto(text, out)` writes what fits and says so in `{ read, written }`,
|
|
1198
|
+
`readSync(fd, buffer)` says how many bytes it read. Read the answer and act on it.
|
|
1199
|
+
|
|
1200
|
+
```ts bad unused-answer
|
|
1201
|
+
export function clean(name: string): string {
|
|
1202
|
+
name.trim();
|
|
1203
|
+
return name;
|
|
1204
|
+
}
|
|
1205
|
+
```
|
|
1206
|
+
|
|
1207
|
+
```ts good
|
|
1208
|
+
export function clean(name: string): string {
|
|
1209
|
+
return name.trim();
|
|
1210
|
+
}
|
|
1211
|
+
```
|
|
1212
|
+
|
|
1213
|
+
An argument named after another parameter of the function than the one it lands in
|
|
1214
|
+
(`misplaced-argument`, a warning) is the sign of a parameter inserted in front, or two arguments
|
|
1215
|
+
swapped: `corner(x, y)` after `corner(size, x, y)` gained `size`. Pass each argument where its
|
|
1216
|
+
parameter is; a function of several values of one type is safer with an object
|
|
1217
|
+
(`area({ width, height })`).
|
|
1218
|
+
|
|
1219
|
+
## A promise used as its value
|
|
1220
|
+
|
|
1221
|
+
A promise read where its value is meant answers wrong without failing: `isErr(load())` is
|
|
1222
|
+
always `false` (to TypeScript a `Promise<Result<T, E>>` is a `Result`, whose value is the
|
|
1223
|
+
promise), `` `${count()}` `` is `[object Promise]`, `ids.filter(async ...)` keeps every id.
|
|
1224
|
+
std's types refuse the first (`tsc` says *this is a promise: `await` it, then pass the value*);
|
|
1225
|
+
`promise-as-value` reports the rest. The fix is the `await`, inside an `async` function; for a
|
|
1226
|
+
callback a built-in reads right away, decide each item where its answer is known, in a
|
|
1227
|
+
`for...of` with `await`. A dropped call that can't reject is `floating-promise` (a warning):
|
|
1228
|
+
`await` it where what follows needs it, or write `void` where it runs on its own on purpose.
|
|
1229
|
+
|
|
1230
|
+
```ts bad promise-as-value floating-promise
|
|
1231
|
+
async function allowed(id: string): Promise<boolean> {
|
|
1232
|
+
return id.startsWith("u-");
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
async function audit(ids: readonly string[]): Promise<void> {
|
|
1236
|
+
console.log(ids.length);
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
export function visible(ids: readonly string[]): string[] {
|
|
1240
|
+
const kept = ids.filter(async (id) => await allowed(id));
|
|
1241
|
+
audit(kept);
|
|
1242
|
+
return kept;
|
|
1243
|
+
}
|
|
1244
|
+
```
|
|
1245
|
+
|
|
1246
|
+
```ts good
|
|
1247
|
+
async function allowed(id: string): Promise<boolean> {
|
|
1248
|
+
return id.startsWith("u-");
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
async function audit(ids: readonly string[]): Promise<void> {
|
|
1252
|
+
console.log(ids.length);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
export async function visible(ids: readonly string[]): Promise<string[]> {
|
|
1256
|
+
const kept: string[] = [];
|
|
1257
|
+
for (const id of ids) if (await allowed(id)) kept.push(id);
|
|
1258
|
+
// The audit runs on its own: nothing below needs it done.
|
|
1259
|
+
void audit(kept);
|
|
1260
|
+
return kept;
|
|
1261
|
+
}
|
|
1262
|
+
```
|
|
1263
|
+
|
|
1264
|
+
## A value used after it was used up
|
|
1265
|
+
|
|
1266
|
+
Some operations use a value up, and the types don't say so: after `buf.transfer()` (or a
|
|
1267
|
+
transfer list: `worker.postMessage(buf, [buf])`) the buffer is detached, a generator or a
|
|
1268
|
+
`list.values()` iterator runs once, a body is read once, a stream locked by `getReader()` can't
|
|
1269
|
+
be read another way, a closed socket sends nothing (`use-after-consume`, an error). The fix is
|
|
1270
|
+
in the order or in a copy: read what you need before the transfer, collect an iterator once
|
|
1271
|
+
(`[...it]`) or make a new one, keep what the body gave, transfer a copy (`buf.slice(0)`).
|
|
1272
|
+
|
|
1273
|
+
```ts bad use-after-consume
|
|
1274
|
+
function* ids(): Generator<string> {
|
|
1275
|
+
yield "a";
|
|
1276
|
+
yield "b";
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
export function twice(): string {
|
|
1280
|
+
const all = ids();
|
|
1281
|
+
const first = [...all].join(",");
|
|
1282
|
+
return `${first} / ${[...all].join(",")}`;
|
|
1283
|
+
}
|
|
1284
|
+
```
|
|
1285
|
+
|
|
1286
|
+
```ts good
|
|
1287
|
+
function* ids(): Generator<string> {
|
|
1288
|
+
yield "a";
|
|
1289
|
+
yield "b";
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
export function twice(): string {
|
|
1293
|
+
const all = [...ids()];
|
|
1294
|
+
return `${all.join(",")} / ${all.join(",")}`;
|
|
1295
|
+
}
|
|
1296
|
+
```
|
|
1297
|
+
|
|
1298
|
+
A `Result` kept in a local is the same kind of mistake when nothing looks at it on some path:
|
|
1299
|
+
`const r = save(x); console.log(r); return true;` drops the error (`must-use-result`). Check it
|
|
1300
|
+
where it is made, or return it.
|
|
1301
|
+
|
|
1302
|
+
## Text given to a sink
|
|
1303
|
+
|
|
1304
|
+
`innerHTML`, `href`, `new Function`, `exec`, `readFile`, `new RegExp`, `db.exec` do what the text
|
|
1305
|
+
says: parse it as markup, follow it (`javascript:` runs), run it, hand it to a shell, open the path
|
|
1306
|
+
it spells, compile it, run it as SQL (`markup-sink`, `url-sink`, `code-sink`, `command-sink`,
|
|
1307
|
+
`path-sink`, `pattern-sink`, `sql-sink`). Each takes a constant the source shows, or its brand
|
|
1308
|
+
from the constructor that checks it: `escapeHtml(text)` or a `defineSanitizer` sanitizer (`Html`),
|
|
1309
|
+
`safeHref(url)` (`SafeUrl`), `pathUnder(root, name)` (`SafePath`), `escapeRegExp(text)`
|
|
1310
|
+
(`RegexSource`). Code, shell commands and SQL have no constructor: write the code, run the program
|
|
1311
|
+
without a shell with the data as arguments, bind the data to placeholders. A helper that takes a
|
|
1312
|
+
`string` and gives it to a sink is reported in the helper: type its parameter with the brand, and
|
|
1313
|
+
its callers make one. `path-sink` reports only in code a request, a socket's data or a message
|
|
1314
|
+
reaches (a handler the runtime calls with outside data, and what it calls), and only from
|
|
1315
|
+
`safe-ts check`: a build script's paths are its operator's.
|
|
1316
|
+
|
|
1317
|
+
```ts bad markup-sink
|
|
1318
|
+
export function showName(name: string): void {
|
|
1319
|
+
const el = document.createElement("b");
|
|
1320
|
+
el.innerHTML = name;
|
|
1321
|
+
document.body.append(el);
|
|
1322
|
+
}
|
|
1323
|
+
```
|
|
1324
|
+
|
|
1325
|
+
```ts good
|
|
1326
|
+
export function showName(name: string): void {
|
|
1327
|
+
const el = document.createElement("b");
|
|
1328
|
+
el.textContent = name;
|
|
1329
|
+
document.body.append(el);
|
|
1330
|
+
}
|
|
1331
|
+
```
|
|
1332
|
+
|
|
1333
|
+
```ts
|
|
1334
|
+
// path-sink, from `safe-ts check`: a request reaches it
|
|
1335
|
+
import { createServer } from "node:http";
|
|
1336
|
+
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
|
|
1337
|
+
import { isErr } from "@evobug_com/safe-ts-std/result";
|
|
1338
|
+
|
|
1339
|
+
async function avatar(dir: string, user: string): Promise<string> {
|
|
1340
|
+
const text = await readFile(`${dir}/${user}.svg`, "utf8");
|
|
1341
|
+
return isErr(text) ? "" : text;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
export const server = createServer((req, res) => {
|
|
1345
|
+
avatar(process.cwd(), req.url ?? "").then(
|
|
1346
|
+
(svg) => res.end(svg),
|
|
1347
|
+
() => res.end(),
|
|
1348
|
+
);
|
|
1349
|
+
});
|
|
1350
|
+
```
|
|
1351
|
+
|
|
1352
|
+
```ts good
|
|
1353
|
+
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
|
|
1354
|
+
import { join } from "node:path";
|
|
1355
|
+
import { pathUnder } from "@evobug_com/safe-ts-std/path";
|
|
1356
|
+
import { isErr } from "@evobug_com/safe-ts-std/result";
|
|
1357
|
+
|
|
1358
|
+
const AVATARS = join(import.meta.dirname, "avatars");
|
|
1359
|
+
|
|
1360
|
+
export async function avatar(user: string): Promise<string> {
|
|
1361
|
+
const file = pathUnder(AVATARS, `${user}.svg`);
|
|
1362
|
+
if (isErr(file)) return "";
|
|
1363
|
+
const text = await readFile(file, "utf8");
|
|
1364
|
+
return isErr(text) ? "" : text;
|
|
1365
|
+
}
|
|
1366
|
+
```
|
|
1367
|
+
|
|
1368
|
+
A value the project vouches for that std has no brand for (an SQL fragment, an id a parser made)
|
|
1369
|
+
is a brand of its own: `Brand<"Sql">`, `brandConstructor("Sql", make)`, `brandSinks("Sql",
|
|
1370
|
+
["pg Pool#query"])` (docs: proof types, brands of your own).
|
|
1371
|
+
|
|
1372
|
+
## State across an await
|
|
1373
|
+
|
|
1374
|
+
Between two `await`s nothing else runs; across one, anything can. Shared state (a field of
|
|
1375
|
+
`this`, module state, a local an `async` callback captures) read before an `await` is stale after
|
|
1376
|
+
it: writing back what was made from it loses a concurrent change, and acting on a check made
|
|
1377
|
+
before it lets two callers both pass (`stale-across-await`, a warning). Read after the `await`;
|
|
1378
|
+
claim the work before the first one (an in-flight promise in a map, a flag set right after its
|
|
1379
|
+
test). A `Mut` parameter is the caller's loan to this call alone: two at once are `aliased-mut`'s.
|
|
1380
|
+
|
|
1381
|
+
```ts bad stale-across-await
|
|
1382
|
+
async function price(id: string): Promise<number> {
|
|
1383
|
+
await Promise.resolve();
|
|
1384
|
+
return id.length;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
export class Cart {
|
|
1388
|
+
total = 0;
|
|
1389
|
+
async add(id: string): Promise<void> {
|
|
1390
|
+
this.total += await price(id);
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
```
|
|
1394
|
+
|
|
1395
|
+
```ts good
|
|
1396
|
+
async function price(id: string): Promise<number> {
|
|
1397
|
+
await Promise.resolve();
|
|
1398
|
+
return id.length;
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
export class Cart {
|
|
1402
|
+
total = 0;
|
|
1403
|
+
async add(id: string): Promise<void> {
|
|
1404
|
+
const amount = await price(id);
|
|
1405
|
+
this.total += amount;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
```
|
|
1409
|
+
|
|
1410
|
+
## What happened during an await
|
|
1411
|
+
|
|
1412
|
+
The world moves on during an `await`. An event that happens once (`close` on a socket or stream,
|
|
1413
|
+
`abort` on a signal, a page's `load`) may come while the function waits: a listener added after
|
|
1414
|
+
the `await` never runs (`late-listener`, an error). Add it before the first `await`, or test what
|
|
1415
|
+
says it happened (`conn.closed`, `signal.aborted`, `document.readyState`) after waiting. A
|
|
1416
|
+
`useTask` / `latest` run may be superseded while it waits: what it writes itself after the
|
|
1417
|
+
`await` lands after the newer run's (`superseded-task-write`, an error). Return the value for the
|
|
1418
|
+
task to hold, or test `signal.aborted` after the `await`, or hand the signal to the awaited call.
|
|
1419
|
+
|
|
1420
|
+
```ts bad late-listener
|
|
1421
|
+
import type { Socket } from "node:net";
|
|
1422
|
+
|
|
1423
|
+
declare function firstPage(): Promise<string>;
|
|
1424
|
+
|
|
1425
|
+
export async function stream(conn: Socket, unsubscribe: () => void): Promise<void> {
|
|
1426
|
+
conn.write(await firstPage());
|
|
1427
|
+
conn.once("close", unsubscribe);
|
|
1428
|
+
}
|
|
1429
|
+
```
|
|
1430
|
+
|
|
1431
|
+
```ts good
|
|
1432
|
+
import type { Socket } from "node:net";
|
|
1433
|
+
|
|
1434
|
+
declare function firstPage(): Promise<string>;
|
|
1435
|
+
|
|
1436
|
+
export async function stream(conn: Socket, unsubscribe: () => void): Promise<void> {
|
|
1437
|
+
conn.once("close", unsubscribe);
|
|
1438
|
+
conn.write(await firstPage());
|
|
1439
|
+
}
|
|
1440
|
+
```
|
|
1441
|
+
|
|
1442
|
+
```ts bad superseded-task-write
|
|
1443
|
+
import { useTask } from "@evobug_com/safe-ts-vue/task";
|
|
1444
|
+
import { ref } from "vue";
|
|
1445
|
+
|
|
1446
|
+
declare function readFile(name: string): Promise<string>;
|
|
1447
|
+
|
|
1448
|
+
export function useViewer() {
|
|
1449
|
+
const open = ref("");
|
|
1450
|
+
const pick = useTask(async (_signal, name: string): Promise<void> => {
|
|
1451
|
+
open.value = await readFile(name);
|
|
1452
|
+
});
|
|
1453
|
+
return { open, pick };
|
|
1454
|
+
}
|
|
1455
|
+
```
|
|
1456
|
+
|
|
1457
|
+
```ts good
|
|
1458
|
+
import { useTask } from "@evobug_com/safe-ts-vue/task";
|
|
1459
|
+
|
|
1460
|
+
declare function readFile(name: string, init?: { signal?: AbortSignal }): Promise<string>;
|
|
1461
|
+
|
|
1462
|
+
export function useViewer() {
|
|
1463
|
+
return useTask((signal, name: string) => readFile(name, { signal }));
|
|
1464
|
+
}
|
|
1465
|
+
```
|
|
1466
|
+
|
|
1467
|
+
## A promise that never settles, a resource kept
|
|
1468
|
+
|
|
1469
|
+
A `new Promise` whose executor has a path that neither resolves nor rejects it hangs whoever
|
|
1470
|
+
awaits it (`promise-never-settles`, an error): settle it on every path, in the `catch` too, or hand
|
|
1471
|
+
`resolve` to a timer or a listener that will. A resource acquired in a function (a file handle,
|
|
1472
|
+
an interval, a server, an observer) and released on one path only stays held on the others, the
|
|
1473
|
+
path where an `await` rejects, a call throws (even one a caller catches) or `q(...)` returns the
|
|
1474
|
+
error included (`unreleased-resource`, a
|
|
1475
|
+
warning): release it in a `finally`, or `await using` it where it is disposable.
|
|
1476
|
+
|
|
1477
|
+
```ts bad unreleased-resource
|
|
1478
|
+
export function poll(tick: () => void, done: () => boolean): void {
|
|
1479
|
+
const id = setInterval(tick, 100);
|
|
1480
|
+
if (done()) return;
|
|
1481
|
+
tick();
|
|
1482
|
+
clearInterval(id);
|
|
1483
|
+
}
|
|
1484
|
+
```
|
|
1485
|
+
|
|
1486
|
+
```ts good
|
|
1487
|
+
export function poll(tick: () => void, done: () => boolean): void {
|
|
1488
|
+
const id = setInterval(tick, 100);
|
|
1489
|
+
try {
|
|
1490
|
+
if (done()) return;
|
|
1491
|
+
tick();
|
|
1492
|
+
} finally {
|
|
1493
|
+
clearInterval(id);
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
```
|
|
1497
|
+
|
|
1498
|
+
## A change left behind, a test already decided
|
|
1499
|
+
|
|
1500
|
+
A change and the change that undoes it (a flag set and cleared, a count up and down, an entry
|
|
1501
|
+
added and removed) with a way out between them that skips the undo leaves the flag on for good
|
|
1502
|
+
(`unbalanced-update`, a warning): an `await` that rejects, a call that throws, a `return`, a
|
|
1503
|
+
`q(...)` that returns the error. Undo it in a `finally`; in a component, `useTask` holds the busy state itself. A test of a
|
|
1504
|
+
place the function just gave a literal (`stop(mut(worker)); if (worker.task !== undefined)`) is
|
|
1505
|
+
decided before it runs (`decided-test`, an error): read what it is about before the change.
|
|
1506
|
+
|
|
1507
|
+
```ts bad unbalanced-update
|
|
1508
|
+
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
|
|
1509
|
+
|
|
1510
|
+
interface Room {
|
|
1511
|
+
users: number;
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
function enter(room: Mut<Room>): void {
|
|
1515
|
+
room.users += 1;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
function leave(room: Mut<Room>): void {
|
|
1519
|
+
room.users -= 1;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
export function visit(room: Mut<Room>, calledOff: boolean): string {
|
|
1523
|
+
enter(mut(room));
|
|
1524
|
+
if (calledOff) return "called off";
|
|
1525
|
+
leave(mut(room));
|
|
1526
|
+
return "done";
|
|
1527
|
+
}
|
|
1528
|
+
```
|
|
1529
|
+
|
|
1530
|
+
```ts good
|
|
1531
|
+
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
|
|
1532
|
+
|
|
1533
|
+
interface Room {
|
|
1534
|
+
users: number;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
function enter(room: Mut<Room>): void {
|
|
1538
|
+
room.users += 1;
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
function leave(room: Mut<Room>): void {
|
|
1542
|
+
room.users -= 1;
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
export function visit(room: Mut<Room>, calledOff: boolean): string {
|
|
1546
|
+
enter(mut(room));
|
|
1547
|
+
try {
|
|
1548
|
+
if (calledOff) return "called off";
|
|
1549
|
+
return "done";
|
|
1550
|
+
} finally {
|
|
1551
|
+
leave(mut(room));
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
```
|
|
1555
|
+
|
|
1556
|
+
## A constructor that calls an overridable method
|
|
1557
|
+
|
|
1558
|
+
A base constructor (or an instance field's initializer) that calls `this.describe()`, which a
|
|
1559
|
+
subclass overrides, runs the override before the subclass's fields are set
|
|
1560
|
+
(`constructor-calls-override`, from `safe-ts check`). Pass the value in (`super(label)`),
|
|
1561
|
+
compute it in a static factory after `new`, or make the method `private`. `class ... extends`
|
|
1562
|
+
itself is fine.
|
|
1563
|
+
|
|
1564
|
+
```ts good
|
|
1565
|
+
export class Base {
|
|
1566
|
+
readonly label: string;
|
|
1567
|
+
constructor(label: string) {
|
|
1568
|
+
this.label = label;
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
export class Named extends Base {
|
|
1573
|
+
constructor(private readonly name: string) {
|
|
1574
|
+
super(name.toUpperCase());
|
|
1575
|
+
}
|
|
1576
|
+
greeting(): string {
|
|
1577
|
+
return `${this.label} (${this.name})`;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
```
|
|
1581
|
+
|
|
1582
|
+
## A table keyed by server data
|
|
1583
|
+
|
|
1584
|
+
`LABELS[state]` with `state` from the server reads `undefined` for a value this build doesn't
|
|
1585
|
+
know (a new state added on the server), and the page crashes on `.tooltip of undefined`. Look
|
|
1586
|
+
it up with `getOwn(table, key, fallback)`: the fallback is typed like the table's values, so a
|
|
1587
|
+
literal fallback doesn't widen them.
|
|
1588
|
+
|
|
1589
|
+
```ts bad no-object-dictionary
|
|
1590
|
+
type State = "open" | "closed";
|
|
1591
|
+
|
|
1592
|
+
const LABELS: Record<string, string> = { open: "Open", closed: "Closed" };
|
|
1593
|
+
|
|
1594
|
+
export function stateLabel(state: string): string {
|
|
1595
|
+
return LABELS[state] ?? "Unknown";
|
|
1596
|
+
}
|
|
1597
|
+
```
|
|
1598
|
+
|
|
1599
|
+
```ts good
|
|
1600
|
+
import { getOwn } from "@evobug_com/safe-ts-std/dict";
|
|
1601
|
+
|
|
1602
|
+
type State = "open" | "closed";
|
|
1603
|
+
|
|
1604
|
+
const LABELS: Record<State, string> = { open: "Open", closed: "Closed" };
|
|
1605
|
+
|
|
1606
|
+
export function stateLabel(state: string): string {
|
|
1607
|
+
return getOwn(LABELS, state, "Unknown");
|
|
1608
|
+
}
|
|
1609
|
+
```
|
|
1610
|
+
|
|
1611
|
+
`satisfies Record<State, string>` (or the annotation) checks that every state this build knows
|
|
1612
|
+
has a row; `getOwn` handles the ones it doesn't, and `constructor` or `toString` as a key.
|
|
1613
|
+
Without the third argument it returns an `Option`.
|
|
1614
|
+
|
|
1615
|
+
## A server value from a list that can grow
|
|
1616
|
+
|
|
1617
|
+
A status or type the server sends from a list it may extend: typed as a union of the strings
|
|
1618
|
+
this build knows, `parseJson` fails the whole response on a new one; typed as `string`, a lookup
|
|
1619
|
+
answers `undefined` for it. `Open<K>` (`@evobug_com/safe-ts-std/open`) keeps both cases:
|
|
1620
|
+
`parseJson` / `validate` give a string `K` lists its variant and any other string `Unknown`,
|
|
1621
|
+
`match` needs an `Unknown` handler, and `lookup(table, value, fallback)` reads an exhaustive
|
|
1622
|
+
table with a fallback for `Unknown` (`TABLE[state.tag]` doesn't compile). Use `getOwn` for a
|
|
1623
|
+
dictionary keyed by any string, `Open` + `lookup` for a field the server fills from a list.
|
|
1624
|
+
|
|
1625
|
+
```ts good
|
|
1626
|
+
import { match } from "@evobug_com/safe-ts-std/enum";
|
|
1627
|
+
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
|
|
1628
|
+
import { type Known, lookup, type Open } from "@evobug_com/safe-ts-std/open";
|
|
1629
|
+
|
|
1630
|
+
export type Issue = { readonly title: string; readonly state: Open<"todo" | "doing" | "done"> };
|
|
1631
|
+
|
|
1632
|
+
const ICONS = { todo: "circle", doing: "half", done: "check" } satisfies Record<Known<Issue["state"]>, string>;
|
|
1633
|
+
|
|
1634
|
+
export function readIssue(text: string): JsonResult<Issue> {
|
|
1635
|
+
return parseJson<Issue>(text);
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
export function label(issue: Issue): string {
|
|
1639
|
+
return match(issue.state, {
|
|
1640
|
+
todo: () => "To do",
|
|
1641
|
+
doing: () => "Doing",
|
|
1642
|
+
done: () => "Done",
|
|
1643
|
+
Unknown: ({ value }) => value,
|
|
1644
|
+
});
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
export function icon(issue: Issue): string {
|
|
1648
|
+
return lookup(ICONS, issue.state, "question");
|
|
1649
|
+
}
|
|
1650
|
+
```
|
|
1651
|
+
|
|
1652
|
+
`value` is the text as it came: send `issue.state.value` back to the server, not the object
|
|
1653
|
+
(`JSON.stringify` of it writes `{"tag":…,"value":…}`). `toOpen(known, text)` makes one from text
|
|
1654
|
+
that doesn't come through `parseJson` (a route parameter).
|
|
1655
|
+
|
|
1656
|
+
## Base64
|
|
1657
|
+
|
|
1658
|
+
`btoa` throws for a character above U+00FF, so `btoa(name)` on user text fails on the first
|
|
1659
|
+
"é" (`unhandled-failure`; `btoa` of digits or of text written out is accepted). `toBase64` from
|
|
1660
|
+
`@evobug_com/safe-ts-std/base64` encodes any string as UTF-8 and can't fail; `fromBase64` and
|
|
1661
|
+
`fromBase64Bytes` return a `Result` (`not base64`, `not UTF-8`). `{ alphabet: "base64url" }`
|
|
1662
|
+
gives the URL-safe alphabet.
|
|
1663
|
+
|
|
1664
|
+
```ts bad unhandled-failure
|
|
1665
|
+
export function avatarKey(name: string): string {
|
|
1666
|
+
return btoa(name);
|
|
1667
|
+
}
|
|
1668
|
+
```
|
|
1669
|
+
|
|
1670
|
+
```ts good
|
|
1671
|
+
import { toBase64 } from "@evobug_com/safe-ts-std/base64";
|
|
1672
|
+
|
|
1673
|
+
export function avatarKey(name: string): string {
|
|
1674
|
+
return toBase64(name, { alphabet: "base64url" });
|
|
1675
|
+
}
|
|
1676
|
+
```
|
|
1677
|
+
|
|
1678
|
+
Where the text is ASCII by contract (an id, a token), keep `btoa` and prove it:
|
|
1679
|
+
`isAscii(id)` (`@evobug_com/safe-ts-std/ascii`) narrows the value to `Ascii`, `asciiOf(n)` makes
|
|
1680
|
+
one from a number, and `btoa` of an `Ascii` isn't reported. The encoded text stays the same.
|
|
1681
|
+
|
|
1682
|
+
For text with characters between U+0080 and U+00FF, `toBase64` writes their UTF-8 bytes where
|
|
1683
|
+
`btoa` wrote one byte each: the encoded text changes. Check what reads it (a server decoding it
|
|
1684
|
+
as Latin-1) before switching, and say so in the hand-off report
|
|
1685
|
+
([behaviour.md](behaviour.md)). Don't wrap `btoa` in `unsafe(...)` to keep the old output
|
|
1686
|
+
unless the architecture document lists it.
|
|
1687
|
+
|
|
1688
|
+
## A built-in that throws on data
|
|
1689
|
+
|
|
1690
|
+
`unhandled-failure` reports the language's built-ins that throw for a value their types allow
|
|
1691
|
+
([builtins.md in the docs](https://safe-ts.evobug-pages.com/guide/builtins)): `reduce` without an
|
|
1692
|
+
initial value on a list that may be empty, `toISOString` of a date parsed from text, and
|
|
1693
|
+
`toFixed`, `toString(radix)`, `repeat`, `String.fromCodePoint`, `new Array(n)`, `BigInt(n)`, a
|
|
1694
|
+
locale or time zone given to `Intl`, when the argument comes from data (a parameter, a field,
|
|
1695
|
+
parsed text); bigint `/` by a divisor that may be `0n`. Write the form that can't fail; don't
|
|
1696
|
+
wrap these in `unsafe(...)` to quiet them:
|
|
1697
|
+
|
|
1698
|
+
- `reduce`: pass the initial value the reduction starts from (`0` for a sum), or check
|
|
1699
|
+
`list.length > 0` first where an empty list means something else.
|
|
1700
|
+
- a date from text: keep it in a `const` and check `Number.isNaN(date.getTime())` first; return
|
|
1701
|
+
an error from the function, as the input was wrong.
|
|
1702
|
+
- an argument from a caller: check the range first (`if (digits < 0 || digits > 100) ...`), or
|
|
1703
|
+
clamp it (`Math.min(100, Math.max(0, digits))`); to pad text use `padStart` / `padEnd`, not
|
|
1704
|
+
`repeat`.
|
|
1705
|
+
- a locale or time zone from settings: make the formatter once, in `unsafe(...)`, where the
|
|
1706
|
+
value enters the program, and pass the formatter on.
|
|
1707
|
+
- a bigint divisor: check `d === 0n` first.
|
|
1708
|
+
|
|
1709
|
+
```ts bad unhandled-failure
|
|
1710
|
+
export function column(text: string, width: number, digits: number, n: number): string {
|
|
1711
|
+
return " ".repeat(width - text.length) + text + n.toFixed(digits);
|
|
1712
|
+
}
|
|
1713
|
+
```
|
|
1714
|
+
|
|
1715
|
+
```ts good
|
|
1716
|
+
export function column(text: string, width: number, digits: number, n: number): string {
|
|
1717
|
+
const shown = digits >= 0 && digits <= 20 ? n.toFixed(digits) : n.toFixed(2);
|
|
1718
|
+
return text.padStart(width) + shown;
|
|
1719
|
+
}
|
|
1720
|
+
```
|
|
1721
|
+
|
|
1722
|
+
## A trusted boundary
|
|
1723
|
+
|
|
1724
|
+
A value no check fits, or not worth one, that another part of the same program made (a
|
|
1725
|
+
worker of the same build that posts only one message type): `trust<T>(value)` from
|
|
1726
|
+
`@evobug_com/safe-ts-std/result`. It does nothing at runtime, is searchable, and `safe-ts check`
|
|
1727
|
+
counts it in its escape-hatches line, so it replaces the `as T` and the overload or guard that
|
|
1728
|
+
hid one (`no-overload`, `no-type-predicate`). Data from outside the program (the network, storage, a file) is validated instead.
|
|
1729
|
+
|
|
1730
|
+
```ts bad no-unchecked-cast
|
|
1731
|
+
type Progress = { readonly done: number; readonly total: number };
|
|
1732
|
+
|
|
1733
|
+
export function onProgress(event: MessageEvent<unknown>, show: (progress: Progress) => void): void {
|
|
1734
|
+
show(event.data as Progress);
|
|
1735
|
+
}
|
|
1736
|
+
```
|
|
1737
|
+
|
|
1738
|
+
```ts good
|
|
1739
|
+
import { trust } from "@evobug_com/safe-ts-std/result";
|
|
1740
|
+
|
|
1741
|
+
type Progress = { readonly done: number; readonly total: number };
|
|
1742
|
+
|
|
1743
|
+
export function onProgress(event: MessageEvent<unknown>, show: (progress: Progress) => void): void {
|
|
1744
|
+
// The worker posts only `Progress` messages (worker.ts, same build).
|
|
1745
|
+
show(trust<Progress>(event.data));
|
|
1746
|
+
}
|
|
1747
|
+
```
|
|
1748
|
+
|
|
1749
|
+
Every `trust` is listed in the architecture document's boundaries section, with the reason
|
|
1750
|
+
([escape-hatches.md](escape-hatches.md)).
|
|
1751
|
+
|
|
1752
|
+
## Strict code with legacy callers that pass null
|
|
1753
|
+
|
|
1754
|
+
A function migrated before its callers still gets `null` from the legacy ones. `LegacyNull`
|
|
1755
|
+
(`@evobug_com/safe-ts-std/result`) is the documented bridge: `Option<T> | LegacyNull` accepts
|
|
1756
|
+
the `null` without one written in the strict file, and is counted. Drop it once no caller passes
|
|
1757
|
+
`null`; a `null` that means something on the wire is `JsonNull`, not this.
|
|
1758
|
+
|
|
1759
|
+
```ts bad no-null
|
|
1760
|
+
export function heading(title: string | null | undefined): string {
|
|
1761
|
+
return title ?? "Untitled";
|
|
1762
|
+
}
|
|
1763
|
+
```
|
|
1764
|
+
|
|
1765
|
+
```ts good
|
|
1766
|
+
import type { LegacyNull, Option } from "@evobug_com/safe-ts-std/result";
|
|
1767
|
+
|
|
1768
|
+
// Legacy callers (src/reports, marked legacy) still pass `null` for "no title". Goes with them.
|
|
1769
|
+
export function heading(title: Option<string> | LegacyNull): string {
|
|
1770
|
+
return title ?? "Untitled";
|
|
1771
|
+
}
|
|
1772
|
+
```
|
|
1773
|
+
|
|
1774
|
+
Don't invent a project-local bridge type (`UiLegacyNull`, `Nullable<T>`): the census and
|
|
1775
|
+
`safe-ts check` count `LegacyNull` and not those.
|
|
1776
|
+
|
|
1777
|
+
## Command-line arguments
|
|
1778
|
+
|
|
1779
|
+
`parseArgs` from `node:util` throws on an unknown option or a missing value. With the Node pack
|
|
1780
|
+
(`@evobug_com/safe-ts-feature-node`), its safe version returns a `Result`, with the values
|
|
1781
|
+
typed by the options as Node's own.
|
|
1782
|
+
|
|
1783
|
+
```ts bad unhandled-failure
|
|
1784
|
+
import { parseArgs } from "node:util";
|
|
1785
|
+
|
|
1786
|
+
export function portText(): string {
|
|
1787
|
+
const { values } = parseArgs({ options: { port: { type: "string" } } });
|
|
1788
|
+
return values.port ?? "8080";
|
|
1789
|
+
}
|
|
1790
|
+
```
|
|
1791
|
+
|
|
1792
|
+
```ts good
|
|
1793
|
+
import { parseArgs } from "@evobug_com/safe-ts-feature-node/util";
|
|
1794
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
1795
|
+
import { q, type Result } from "@evobug_com/safe-ts-std/result";
|
|
1796
|
+
|
|
1797
|
+
export type ArgsError = Enum<{ BadArgs: { message: string } }>;
|
|
1798
|
+
export const ArgsError = constructors<ArgsError>();
|
|
1799
|
+
|
|
1800
|
+
const badArgs = (error: Error): ArgsError => ArgsError.BadArgs({ message: error.message });
|
|
1801
|
+
|
|
1802
|
+
export function portText(): Result<string, ArgsError> {
|
|
1803
|
+
const parsed = q(parseArgs({ options: { port: { type: "string" } } }), badArgs);
|
|
1804
|
+
return parsed.values.port ?? "8080";
|
|
1805
|
+
}
|
|
1806
|
+
```
|
|
1807
|
+
|
|
1808
|
+
## IndexedDB
|
|
1809
|
+
|
|
1810
|
+
The request-and-callback API (`indexedDB.open(...)`, `onsuccess`, `onerror`, `onupgradeneeded`)
|
|
1811
|
+
throws in some calls and reports in callbacks in others. The browser pack's
|
|
1812
|
+
`@evobug_com/safe-ts-feature-browser/indexeddb` settles each request as a `Promise<Result>` (or a
|
|
1813
|
+
`Result` for the calls that only throw), with typed errors: `open`, `createObjectStore` (in
|
|
1814
|
+
`upgrade`), `transaction`, `objectStore`, `get` (with a validator), `getGuarded`, `put`,
|
|
1815
|
+
`deleteKey`, `clear`, `commit`. Name the error the callers see as an `Enum` of the kinds the UI
|
|
1816
|
+
handles. Here that is one kind, `Storage`, whose line `describeError` writes from whichever
|
|
1817
|
+
pack error it was.
|
|
1818
|
+
|
|
1819
|
+
```ts good
|
|
1820
|
+
import { commit, createObjectStore, get, objectStore, open, put, transaction } from "@evobug_com/safe-ts-feature-browser/indexeddb";
|
|
1821
|
+
import { validate } from "@evobug_com/safe-ts-std/json";
|
|
1822
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
1823
|
+
import { describeError, type Option, q, type Result } from "@evobug_com/safe-ts-std/result";
|
|
1824
|
+
|
|
1825
|
+
type Draft = { readonly id: string; readonly text: string };
|
|
1826
|
+
|
|
1827
|
+
export type DraftError = Enum<{ Storage: { reason: string } }>;
|
|
1828
|
+
export const DraftError = constructors<DraftError>();
|
|
1829
|
+
|
|
1830
|
+
const storage = (error: unknown): DraftError => DraftError.Storage({ reason: describeError(error) });
|
|
1831
|
+
|
|
1832
|
+
const openDrafts = (): Promise<Result<IDBDatabase, unknown>> =>
|
|
1833
|
+
open(indexedDB, "app", { version: 1, upgrade: (database) => createObjectStore(database, "drafts", { keyPath: "id" }) });
|
|
1834
|
+
|
|
1835
|
+
export async function saveDraft(draft: Draft): Promise<Result<void, DraftError>> {
|
|
1836
|
+
const db = q(await openDrafts(), storage);
|
|
1837
|
+
const tx = q(transaction(db, "drafts", "readwrite"), storage);
|
|
1838
|
+
const store = q(objectStore(tx, "drafts"), storage);
|
|
1839
|
+
q(await put(store, draft), storage);
|
|
1840
|
+
return q(await commit(tx), storage);
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
export async function loadDraft(id: string): Promise<Result<Option<Draft>, DraftError>> {
|
|
1844
|
+
const db = q(await openDrafts(), storage);
|
|
1845
|
+
const tx = q(transaction(db, "drafts"), storage);
|
|
1846
|
+
const store = q(objectStore(tx, "drafts"), storage);
|
|
1847
|
+
return q(await get(store, id, (value) => validate<Draft>(value)), storage);
|
|
1848
|
+
}
|
|
1849
|
+
```
|
|
1850
|
+
|
|
1851
|
+
Call `commit(tx)` right after the last request: awaiting something else in between lets the
|
|
1852
|
+
transaction finish without you (`TransactionInactiveError`).
|
|
1853
|
+
|
|
1854
|
+
## A bug inside a Result-returning call
|
|
1855
|
+
|
|
1856
|
+
`unsafeAsync(() => search(text))` around a function of your own that returns a `Result` merges
|
|
1857
|
+
its typed `Err` with whatever it throws by mistake into one `Err<unknown>`, so a bug is shown
|
|
1858
|
+
to the user as an ordinary failure. Pass `Panic`: the throw becomes a `Panic` (not an `Err`),
|
|
1859
|
+
and the returned `Err` keeps its type (guide: Errors, "When you call code that throws").
|
|
1860
|
+
|
|
1861
|
+
```ts good
|
|
1862
|
+
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
1863
|
+
import { isErr, isPanic, Panic, type Result, unsafeAsync } from "@evobug_com/safe-ts-std/result";
|
|
1864
|
+
|
|
1865
|
+
type SendError = Enum<{ Refused: {}; Offline: {} }>;
|
|
1866
|
+
|
|
1867
|
+
declare function send(message: string): Promise<Result<void, SendError>>;
|
|
1868
|
+
|
|
1869
|
+
export async function deliver(message: string): Promise<string> {
|
|
1870
|
+
// A throw from send() is a bug: kept apart from the errors it returns.
|
|
1871
|
+
const sent = await unsafeAsync(() => send(message), Panic);
|
|
1872
|
+
if (isPanic(sent)) {
|
|
1873
|
+
console.error("bug in send", sent.reason);
|
|
1874
|
+
return "Not delivered";
|
|
1875
|
+
}
|
|
1876
|
+
if (!isErr(sent)) return "Delivered";
|
|
1877
|
+
return match(sent.error, { Refused: () => "The server refused it", Offline: () => "Offline: try again later" });
|
|
1878
|
+
}
|
|
1879
|
+
```
|
|
1880
|
+
|
|
1881
|
+
Better still, don't wrap your own code at all: if it can throw, that is the bug to fix. With the
|
|
1882
|
+
idiomatic layer on, `unsafe-project-call` reports `unsafe` / `unsafeAsync` without `Panic`
|
|
1883
|
+
around a call of the project's own function that the checker finds nothing to throw in.
|
|
1884
|
+
|
|
1885
|
+
## panic on a loading state
|
|
1886
|
+
|
|
1887
|
+
`panic` is for invariants nothing can handle (a table built at load time with a name listed
|
|
1888
|
+
twice). A store read before its data arrived is a state of the page, not an invariant: show a
|
|
1889
|
+
wait (an `AsyncState`, `Option`), don't crash. With the idiomatic layer on, `panic-on-loading`
|
|
1890
|
+
reports a `panic` under a condition that names a loading flag (`hydrated`, `isLoading`, ...) or
|
|
1891
|
+
a `Loading` / `Idle` variant; it goes by names, so a `panic` on a loading state under another
|
|
1892
|
+
name is left to review.
|
|
1893
|
+
|
|
1894
|
+
```ts bad panic-on-loading
|
|
1895
|
+
import { type Option, panic } from "@evobug_com/safe-ts-std/result";
|
|
1896
|
+
|
|
1897
|
+
type Session = { readonly hydrated: boolean; readonly user: Option<{ readonly name: string }> };
|
|
1898
|
+
|
|
1899
|
+
export function userName(session: Session): string {
|
|
1900
|
+
if (!session.hydrated || session.user === undefined) panic("the session is not hydrated");
|
|
1901
|
+
return session.user.name;
|
|
1902
|
+
}
|
|
1903
|
+
```
|
|
1904
|
+
|
|
1905
|
+
```ts good
|
|
1906
|
+
import type { AsyncState } from "@evobug_com/safe-ts-std/async-state";
|
|
1907
|
+
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
1908
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
1909
|
+
|
|
1910
|
+
type User = { readonly name: string };
|
|
1911
|
+
type LoadError = Enum<{ Offline: {}; Status: { status: number } }>;
|
|
1912
|
+
type Session = { readonly user: AsyncState<Option<User>, LoadError> };
|
|
1913
|
+
|
|
1914
|
+
export function userLine(session: Session): string {
|
|
1915
|
+
return match(session.user, {
|
|
1916
|
+
Ready: ({ value }) => value?.name ?? "Signed out",
|
|
1917
|
+
Failed: () => "Couldn't load your account",
|
|
1918
|
+
_: () => "Loading…",
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
```
|
|
1922
|
+
|
|
1923
|
+
## A method handed over by name
|
|
1924
|
+
|
|
1925
|
+
`queueMicrotask(this.flush)`, `items.forEach(this.add)`, `const { flush } = buffer` and
|
|
1926
|
+
`onClick={this.save}` hand over the method without its object: when it runs, `this` is
|
|
1927
|
+
`undefined` and the first `this.x` throws `TypeError`. TypeScript accepts it; `unbound-method`
|
|
1928
|
+
reports it for a method that uses `this`. Write an arrow that calls the method on its object
|
|
1929
|
+
where it is handed over, or make it an arrow-function field when it is always handed over (a
|
|
1930
|
+
listener). The quick fix binds it (`this.flush.bind(this)`), which also works.
|
|
1931
|
+
|
|
1932
|
+
```ts bad unbound-method
|
|
1933
|
+
export class Buffer {
|
|
1934
|
+
private readonly lines: string[] = [];
|
|
1935
|
+
flush(): void {
|
|
1936
|
+
this.lines.length = 0;
|
|
1937
|
+
}
|
|
1938
|
+
later(): void {
|
|
1939
|
+
queueMicrotask(this.flush);
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
```
|
|
1943
|
+
|
|
1944
|
+
```ts good
|
|
1945
|
+
export class Buffer {
|
|
1946
|
+
private readonly lines: string[] = [];
|
|
1947
|
+
flush(): void {
|
|
1948
|
+
this.lines.length = 0;
|
|
1949
|
+
}
|
|
1950
|
+
later(): void {
|
|
1951
|
+
queueMicrotask(() => this.flush());
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
```
|
|
1955
|
+
|
|
1956
|
+
## A parameter the function changes
|
|
1957
|
+
|
|
1958
|
+
A function that changes what it is given declares the parameter `Mut<T>`, and every caller
|
|
1959
|
+
lends the value with `mut(value)`, like Rust's `&mut value`; everything else only reads its
|
|
1960
|
+
parameters (`no-param-mutation`). TypeScript refuses a value passed to a `Mut` parameter without
|
|
1961
|
+
`mut(...)` and checks `Mut` in both directions: a `Dog[]` isn't a `Mut<Animal[]>`, and a function
|
|
1962
|
+
taking `Mut<T>` doesn't fit a callback slot of type `(value: T) => void`. `missing-mut` reports a
|
|
1963
|
+
call without the loan (its fix writes it), `aliased-mut` a call that lends `x` and also gets `x`
|
|
1964
|
+
or a part of it.
|
|
1965
|
+
|
|
1966
|
+
```ts bad missing-mut no-tsc
|
|
1967
|
+
import type { Mut } from "@evobug_com/safe-ts-std/mut";
|
|
1968
|
+
|
|
1969
|
+
type Cart = { items: string[] };
|
|
1970
|
+
|
|
1971
|
+
function addItem(cart: Mut<Cart>, item: string): void {
|
|
1972
|
+
cart.items.push(item);
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
export function restock(cart: Mut<Cart>, items: readonly string[]): void {
|
|
1976
|
+
for (const item of items) addItem(cart, item);
|
|
1977
|
+
}
|
|
1978
|
+
```
|
|
1979
|
+
|
|
1980
|
+
```ts good
|
|
1981
|
+
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
|
|
1982
|
+
|
|
1983
|
+
type Cart = { items: string[] };
|
|
1984
|
+
|
|
1985
|
+
function addItem(cart: Mut<Cart>, item: string): void {
|
|
1986
|
+
cart.items.push(item);
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
export function restock(cart: Mut<Cart>, items: readonly string[]): void {
|
|
1990
|
+
for (const item of items) addItem(mut(cart), item);
|
|
1991
|
+
}
|
|
1992
|
+
```
|
|
1993
|
+
|
|
1994
|
+
An optional value stays optional (`mut(maybe)` for an `Option<Mut<T>>` parameter); a fresh
|
|
1995
|
+
literal gets the parameter's type first (`const out: number[] = []`, then `mut(out)`); a list
|
|
1996
|
+
whose elements are changed is `readonly Mut<T>[]`, lent with `mutEach(items)` (no copy; the
|
|
1997
|
+
transform erases it, as it erases `mut(x)`).
|
|
1998
|
+
Don't give `mut` a type argument except for a fresh literal (`mut<Cost>({ ... })`):
|
|
1999
|
+
`mut<Animal[]>(dogs)` is a cast (`no-unchecked-cast`). A value with more properties than the
|
|
2000
|
+
parameter names is lent as it is (a subclass, a `Tree` for `Mut<Entity>`); one whose writable
|
|
2001
|
+
property is narrower is refused, rightly. A member is lent where its union is asked
|
|
2002
|
+
(`Mut<number[]>` as `Mut<number[] | Int32Array>`). Don't make a function generic to get past a refusal: TypeScript lets a
|
|
2003
|
+
generic body write the bound's type into `T`'s narrower property. A union narrowed to one member
|
|
2004
|
+
(`is`, `match`, a tag test) is passed on where that member's `Mut` is asked.
|
|
2005
|
+
|
|
2006
|
+
What is reached through a borrowed value is borrowed too, and `no-param-mutation` says so:
|
|
2007
|
+
|
|
2008
|
+
- **A method of your own class that changes its object** (`c.bump()`, `deps.limiter.take()`):
|
|
2009
|
+
the function takes the object `Mut<Counter>` (also a deps bag whose service it changes:
|
|
2010
|
+
`Mut<Deps>`), and its callers lend it; or it calls the method on what it owns. A getter that
|
|
2011
|
+
changes its object (`mutating-getter`) becomes a method; a memo it fills goes in a
|
|
2012
|
+
`/** @cache */` field. A method lends its own object as `mut<Counter>(this)`.
|
|
2013
|
+
- **A part handed out** (`const inner = peek(o); inner.value = 1`): return `Readonly<Inner>` /
|
|
2014
|
+
`readonly T[]` where callers only read, a copy where they change their own, or take and
|
|
2015
|
+
return `Mut` (`function peekMut(o: Mut<Outer>): Mut<Inner> { return mut(o.inner) }`).
|
|
2016
|
+
- **A borrowed value a class keeps and changes later** (`add(item: Item) { this.items.push(item) }`,
|
|
2017
|
+
then `item.value = 0` in another method; a constructor's `private readonly deps: Deps` whose
|
|
2018
|
+
`deps.metrics.logins++` runs later): declare that parameter `Mut<...>`, so callers write
|
|
2019
|
+
`mut(item)` / `new Service(mut(deps))`; or keep a copy.
|
|
2020
|
+
- **Two loans alive at once** (`aliased-mut`): `await Promise.all([f(mut(x)), g(mut(x))])`,
|
|
2021
|
+
`xs.map(async () => f(mut(x)))` and a loop that pushes `f(mut(x))` into a list become a
|
|
2022
|
+
`for...of` with `await` in it, or one object per call; a promise kept in a `const` is awaited
|
|
2023
|
+
before the object is lent again (quick fix *Await `p` first*) or written by its owner. A
|
|
2024
|
+
listener or a method that starts `f(mut(this.state))` and returns takes turns: chain it
|
|
2025
|
+
(`this.tail = this.tail.then(() => f(mut(this.state)))`) or keep the call in flight and return
|
|
2026
|
+
it to a second caller. A function that starts `f(mut(param))` without awaiting it returns the
|
|
2027
|
+
promise (declared `Promise<...>`) or awaits it, on every way out: what may throw goes before the
|
|
2028
|
+
lend, or the promise is awaited in a `finally` (an exception between the lend and the `await`, a
|
|
2029
|
+
member of the `Promise.all` that rejects first, leaves the call running). Only callees that write the loan after an
|
|
2030
|
+
`await` count (a write of their own answer too: the older answer may land on the newer).
|
|
2031
|
+
- **A `readonly` value given a writable place** (`readonly-dropped`: `const rw: Loose = frozen`,
|
|
2032
|
+
`const PALETTE: Palette = Object.freeze({ ... })` with `Palette`'s fields writable, a `return` of a
|
|
2033
|
+
`Readonly<T>` where `T` is declared): write `readonly` on the place too (`Readonly<Palette>`, the
|
|
2034
|
+
interface's fields `readonly`), or give it a copy it may change (`{ ...frozen }`).
|
|
2035
|
+
- **A shallow copy changed through a field** (`const copy = { ...order }; copy.meta.tag = "x"`,
|
|
2036
|
+
`[...order.lines, extra]` then an element changed, `Object.assign({}, order)`, a rest
|
|
2037
|
+
`const { id, ...rest } = order`, a helper's `return { ...o }`): the copy's own slots are the
|
|
2038
|
+
function's, what they hold is the caller's. Copy that part too (`{ ...order, meta: { ...order.meta
|
|
2039
|
+
} }`, `order.lines.map((l) => ({ ...l }))`), give the field a new value first (`copy.meta = {
|
|
2040
|
+
... }` as a statement right after the copy), or `structuredClone(order)`; don't write
|
|
2041
|
+
`mut({ ...order })` to lend a copy whose fields hold objects.
|
|
2042
|
+
- **A `Sub[]` bound to a writable `Base[]`** (`covariant-alias`): write `readonly Base[]` on the
|
|
2043
|
+
wider side (`ReadonlyMap`, `readonly` fields of your generic type), or bind a copy.
|
|
2044
|
+
- **A handler lent as one that needs more** (`covariant-alias`: `{ onEvent: (a: Animal) => string }`
|
|
2045
|
+
lent as `Mut<{ onEvent: (d: Dog) => string }>`): write the property `readonly` in the type the
|
|
2046
|
+
callee takes (it calls the handler, it doesn't replace it), or give both types the same
|
|
2047
|
+
parameter and result.
|
|
2048
|
+
- **An object a borrowed list holds, changed** (`for (const u of units) u.x = 1`, `find`, `get`, an
|
|
2049
|
+
element of a `filter`ed copy): the function takes `readonly Mut<Unit>[]` (or
|
|
2050
|
+
`ReadonlyMap<K, Mut<V>>`), its callers lend each (`mutEach(units)`); a new list it
|
|
2051
|
+
builds (`filter`, `slice`) is its own to push to.
|
|
2052
|
+
- **A write through a union to a property its members type differently** (`union-tag-write`,
|
|
2053
|
+
`unit.kind = "archer"` on a `Mason | Archer`): put a new object of that member where it is
|
|
2054
|
+
held, or narrow first.
|
|
2055
|
+
|
|
2056
|
+
The fixes ripple once: a function that now takes `Mut<X>` makes its callers lend `x`, and a
|
|
2057
|
+
caller that only borrowed `x` itself gets the same finding. Run `safe-ts migrate mut --write`
|
|
2058
|
+
after declaring, to write the loans.
|
|
2059
|
+
|
|
2060
|
+
## Casts in tests
|
|
2061
|
+
|
|
2062
|
+
`as unknown as Service` and `as never` in tests say a value has a type without anything to
|
|
2063
|
+
back it. `@evobug_com/safe-ts-std/testing` names each need: `fixture<T>(fields)` for a value of a
|
|
2064
|
+
big type with the fields the test needs, `testDouble<T>(fields)` for a fake that throws when
|
|
2065
|
+
code reads a field it wasn't given, `unchecked<T>(value)` for the wrong type on purpose, and
|
|
2066
|
+
`expectPresent(value)` for a lookup the test knows succeeds (guide: Testing, "Partial and fake
|
|
2067
|
+
values"). They are reported outside test files (`test-only-helper`). In test files a cast is
|
|
2068
|
+
reported by `no-unchecked-cast`, whose help there names these helpers; where a project turns
|
|
2069
|
+
that rule off for its tests, `cast-in-test` (idiomatic) still reports `as unknown as T` and
|
|
2070
|
+
`as never`.
|
|
2071
|
+
|
|
2072
|
+
```ts good
|
|
2073
|
+
import assert from "node:assert/strict";
|
|
2074
|
+
import { test } from "node:test";
|
|
2075
|
+
|
|
2076
|
+
import { fixture } from "@evobug_com/safe-ts-std/testing";
|
|
2077
|
+
|
|
2078
|
+
type Invoice = { readonly number: string; readonly total: number; readonly customer: { readonly name: string; readonly email: string } };
|
|
2079
|
+
|
|
2080
|
+
function greeting(invoice: Invoice): string {
|
|
2081
|
+
return `Dear ${invoice.customer.name}`;
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
test("the greeting uses the customer's name", () => {
|
|
2085
|
+
assert.equal(greeting(fixture<Invoice>({ customer: { name: "Ada" } })), "Dear Ada");
|
|
2086
|
+
});
|
|
2087
|
+
```
|
|
2088
|
+
|
|
2089
|
+
## A test that cannot fail
|
|
2090
|
+
|
|
2091
|
+
A test passes when nothing in it fails, so one that checks nothing passes whatever the code
|
|
2092
|
+
does. Reported in test files, as errors: a path to the test's end with no assertion
|
|
2093
|
+
(`test-without-assertion`: none at all, one only inside a branch or after an early `return`, or
|
|
2094
|
+
all of them in a `catch`), an assertion whose outcome is fixed (`assertion-cannot-fail`:
|
|
2095
|
+
`expect(r).toBe(r)`, constants only, `expect(x)` with no matcher, `toBeDefined()` on a value that
|
|
2096
|
+
is always there, the test's own mock), one that runs after the test ended (`deferred-assertion`:
|
|
2097
|
+
a timer, a listener, a `.then` nobody awaits) and one a `catch` swallows
|
|
2098
|
+
(`swallowed-assertion`); `.only` (`focused-test`, an error too); and, as warnings, a skip with
|
|
2099
|
+
no reason (`skipped-test`), two tests of one name (`duplicate-test-name`) and an empty `describe`
|
|
2100
|
+
(`empty-test-suite`). Don't fix one by adding an assertion that restates what the test just
|
|
2101
|
+
computed: assert what the result must be. A test that only checks that the code doesn't throw
|
|
2102
|
+
says so: `assert.doesNotThrow(() => f())`, `await assert.doesNotReject(p)`,
|
|
2103
|
+
`expect(() => f()).not.toThrow()`. A throw is checked with `assert.throws` / `.toThrow()`, not
|
|
2104
|
+
with a `try` / `catch`.
|
|
2105
|
+
|
|
2106
|
+
```ts bad test-without-assertion
|
|
2107
|
+
import { test } from "node:test";
|
|
2108
|
+
|
|
2109
|
+
function total(prices: readonly number[]): number {
|
|
2110
|
+
return prices.reduce((sum, price) => sum + price, 0);
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
test("total adds the prices", () => {
|
|
2114
|
+
total([3, 4]);
|
|
2115
|
+
});
|
|
2116
|
+
```
|
|
2117
|
+
|
|
2118
|
+
```ts good
|
|
2119
|
+
import assert from "node:assert/strict";
|
|
2120
|
+
import { test } from "node:test";
|
|
2121
|
+
|
|
2122
|
+
function total(prices: readonly number[]): number {
|
|
2123
|
+
return prices.reduce((sum, price) => sum + price, 0);
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
test("total adds the prices", () => {
|
|
2127
|
+
assert.equal(total([3, 4]), 7);
|
|
2128
|
+
});
|
|
2129
|
+
```
|
|
2130
|
+
|
|
2131
|
+
A helper the test calls counts when it asserts on every path (also one imported from another
|
|
2132
|
+
file); an unknown function counts only when its name says it checks (`assertValid`,
|
|
2133
|
+
`expectNoErrors`). Every skipped test is counted among the escape hatches (`skippedTests` in the
|
|
2134
|
+
baseline), with a reason or not.
|
|
2135
|
+
|
|
2136
|
+
## A function result the checker cannot read
|
|
2137
|
+
|
|
2138
|
+
The rules that judge a value by its type read the declared return type, or, without one, what
|
|
2139
|
+
each `return` plainly is (a literal, `.length`, arithmetic, a call of a function whose result
|
|
2140
|
+
is known, `err(...)`, a declared local, a class's method, a Vue `ref`). A result made
|
|
2141
|
+
otherwise (`await`, a package's call) is unknown, and those rules say nothing about it. With
|
|
2142
|
+
the idiomatic rules on, `undeclared-return-type` lists each such
|
|
2143
|
+
function; declare what it returns. `safe-ts fix undeclared-return-type <dirs>` writes
|
|
2144
|
+
the type where every `return` names one. Leave a single test undeclared (`return typeof x ===
|
|
2145
|
+
"string"`): TypeScript infers the predicate from it only without a return type.
|
|
2146
|
+
|
|
2147
|
+
```ts good
|
|
2148
|
+
class Cart {
|
|
2149
|
+
constructor(readonly items: readonly string[]) {}
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
export function openCart(items: readonly string[]): Cart {
|
|
2153
|
+
return new Cart(items);
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
export function isText(value: unknown) {
|
|
2157
|
+
return typeof value === "string";
|
|
2158
|
+
}
|
|
2159
|
+
```
|
|
2160
|
+
|
|
2161
|
+
## Code nothing reaches
|
|
2162
|
+
|
|
2163
|
+
An agent that writes a new function leaves the old one. Delete what nothing reaches instead of
|
|
2164
|
+
keeping it "in case": `unused-code` (idiomatic, `safe-ts check` only) reports an export no file
|
|
2165
|
+
of the program imports (and that no entry, package `exports`, `import()`, worker or config file
|
|
2166
|
+
offers outside), and what only such code uses; `unused-private` (idiomatic) a private member
|
|
2167
|
+
nothing in its class uses, or a field written and never read; `unreachable-code` code after a
|
|
2168
|
+
call that never returns, and a fallback after every member of a closed type is handled.
|
|
2169
|
+
`safe-ts fix unused-code <dirs>` deletes what nothing refers to at all; run it again for what
|
|
2170
|
+
that left. A fallback that "can't happen" is `unreachable(x)`: TypeScript checks it, and a
|
|
2171
|
+
member added later fails to compile there.
|
|
2172
|
+
|
|
2173
|
+
```ts good
|
|
2174
|
+
import { unreachable } from "@evobug_com/safe-ts-std/enum";
|
|
2175
|
+
|
|
2176
|
+
type Kind = "a" | "b";
|
|
2177
|
+
|
|
2178
|
+
export function label(kind: Kind): string {
|
|
2179
|
+
if (kind === "a") return "A";
|
|
2180
|
+
if (kind === "b") return "B";
|
|
2181
|
+
return unreachable(kind);
|
|
2182
|
+
}
|
|
2183
|
+
```
|
|
2184
|
+
|
|
2185
|
+
```ts bad unreachable-code
|
|
2186
|
+
type Kind = "a" | "b";
|
|
2187
|
+
|
|
2188
|
+
export function label(kind: Kind): string {
|
|
2189
|
+
if (kind === "a") return "A";
|
|
2190
|
+
if (kind === "b") return "B";
|
|
2191
|
+
return "?";
|
|
2192
|
+
}
|
|
2193
|
+
```
|
|
2194
|
+
|
|
2195
|
+
```ts bad unused-private
|
|
2196
|
+
export class Counter {
|
|
2197
|
+
private count = 0;
|
|
2198
|
+
private last = 0;
|
|
2199
|
+
bump(): number {
|
|
2200
|
+
this.count += 1;
|
|
2201
|
+
this.last = this.count;
|
|
2202
|
+
return this.count;
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
```
|
|
2206
|
+
|
|
2207
|
+
## Event names at both ends
|
|
2208
|
+
|
|
2209
|
+
An event's name is a string at both ends: rename or mistype one and nothing fails, the
|
|
2210
|
+
listener just never runs. Write the name once (an exported `const`, used by the emit and the
|
|
2211
|
+
listener), and give the listener's event its type on the DOM (`(event: MouseEvent) => ...`):
|
|
2212
|
+
TypeScript then refuses a name the element's event map doesn't have. `unknown-event` reports a
|
|
2213
|
+
DOM listener for an event its class never dispatches (`"clik"`), `unmatched-event` a listener
|
|
2214
|
+
nothing emits for and an emit nobody listens for on the same emitter, naming the near miss at
|
|
2215
|
+
both sites (both `safe-ts check` only).
|
|
2216
|
+
|
|
2217
|
+
```ts
|
|
2218
|
+
import { EventEmitter } from "node:events";
|
|
2219
|
+
|
|
2220
|
+
export const UserCreated = "user:created";
|
|
2221
|
+
export type Events = { [UserCreated]: [id: string] };
|
|
2222
|
+
|
|
2223
|
+
export class Users {
|
|
2224
|
+
readonly events = new EventEmitter<Events>();
|
|
2225
|
+
create(id: string): void {
|
|
2226
|
+
this.events.emit(UserCreated, id);
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
```
|