Absence and null: no-null-check-for-undefined, a JSON null kept, no-null at outside types #63

Merged
sionzee merged 2 commits from evobug/fb3-absence into main 2026-11-16 23:46:33 +01:00
Owner

Round 3 of the 0.2.0 adoption feedback, area absence and null (top-ten #1 and #9).

Per feedback item

1. A rule mirroring no-undefined-check-for-null: done. New rule no-null-check-for-undefined, in the default set as an error (it reports only where the type is known to have no null). It reports:

  • === null, !== null, == null, != null;
  • null expected by an assertion: node:assert / node:assert/strict and chai equal, strictEqual, deepEqual, ... (on the module, imported by name, assert.strict.*), also at one element of an array or object literal (assert.deepEqual([a, b], ["paid", null]));
  • chai's isNull / isNotNull, and vitest/jest toBe(null), toEqual(null), toStrictEqual(null), toBeNull(), .not.

A value counts as "no null" when its declared type has none: variables, parameters, destructuring, fields (inherited too, and class fields and parameter properties), return types of the project's functions and methods. It follows imports and re-exports (export * too), array elements, for...of, element callbacks (forEach((x) => ...)), Map#get, Array#find/at/pop, await of a Promise<Option<T>>, ??, ?:, and the packs' Option safe versions. The per-file part (null_check.rs) turns declarations into small shapes; the project pass evaluates them across files.

Left alone: anything that may hold null or whose type isn't known. That covers DOM lookups (they keep toBeNull()), unknown/any, packages' types, generics (first<T>(): Option<T>), ReturnType<...>, and conditional and mapped types.

Decision on #61's check: the safe-version === null report moved from no-null into the new rule (same message wording, Compare with undefined), so each message has one rule. Where the new rule reports a loose == null, no-null's report of that null is dropped, so there are no two reports for one mistake.

Quick fixes: Compare with undefined, Use toBeUndefined(), Use toBeDefined() (for .not.toBeNull()), chai Use isUndefined() / Use isDefined().

2. parseJson / validate keeping a JSON null: done, with types rather than an option.

  • JsonNull: in a type, only a null fits it and the result keeps it. category: string | JsonNull refuses a missing key; category?: string | JsonNull leaves it out; Option<T> | JsonNull gives undefined for missing and null for null. In a dictionary, a null value keeps its key. Works in fromFields and arbitrary too.
  • RawJson: any JSON as JSON.parse gives it, every null kept, so it comes back byte for byte. It is checked like JsonValue (no NaN, class instances or cycles).
  • The default is unchanged (null becomes undefined).
  • jsonNull is now typed JsonNull and documented as the output-format and raw-JSON escape, not only for tests. JSON.stringify of data holding it, or typed with JsonNull fields, isn't reported.
  • No { nulls: "keep" } option: parseJson<JsonValue>(text, { nulls: "keep" }) would hand back nulls that its type says can't be there. The type says it instead.
  • Tests: the discount action ("category": null = every category, missing = refused), a canonical hash of settings with nulls, byte-identical round trips, and arbitrary round trips.

3. no-null accepts null / ?? null where a package's or the platform's type is expected: done, except one case it can't see. This covers the return of a function or arrow declared with such a type (bound(p): SQLInputValue, params.map((p): SQLInputValue => p ?? null), async Promise<T> too) and push/unshift into an array declared with such elements. It also covers the elements of such an array literal, a variable declared with such a type, and assignment to a field of a package's object, also for each child of group.children. It covers methods of values declared with the platform's type (gl.texImage2D(..., null) with gl: WebGL2RenderingContext, or this.#gl), using #57's global types and excluding containers like Map, Array and Record. Last, the null in a el: HTMLElement | null parameter is allowed when the parameter only goes to outside code or is tested (compared, read from, ?., if (el)), and is never returned, stored or passed to the program's own functions. It reuses #46's package_type.

Not covered: TwitchRTS's actual c.parent = null, where c comes from a Set<Container> in a Map value. Without a type checker, nothing declares it there (documented in "What the rule can't see").

4. The null-to-undefined codemod writes x?: Option<T>: done. It does this when every parameter after the one with = null may be left out too. Otherwise the default stays (x: Option<T> = undefined, the same thing).

5. Docs: done.

Upgrading notes:

  • exactOptionalPropertyTypes and kind: c ? undefined : kind: a paragraph in the absence guide (write the two objects, or Option<T>).
  • The adoption guide's codemod section now points to the new rule for code merged later.

Docs pages changed

  • New: docs/rules/no-null-check-for-undefined.md.
  • Updated: docs/rules/no-null.md, docs/guide/absence.md ("null from outside", comparisons both ways, JsonNull, exactOptionalPropertyTypes), docs/guide/json.md ("Keeping a JSON null", replacing "A JSON null in test data"), docs/guide/libraries.md, docs/guide/adoption.md, docs/guide/testing.md.
  • Also updated: docs/README.md and README.md rule tables and std listing, the docs sidebar, CHANGELOG.md (Unreleased: Added and Changed; #61's line now names the new rule).

TwitchRTS check

The branch's own code already carries the hand workarounds, so it has 0 no-null and 0 new-rule reports before and after.

To measure #1, I took the 199 comparison and assertion lines the adoption commit changed by hand from null to undefined (=== null, toBeNull, assert.equal(x, null), ...) and put the null forms back in a scratch copy. Results:

  • main: 0 reports.
  • This branch: 138 reported, all 138 on those lines, 0 anywhere else.
  • The 61 not reported go through generic helpers (defined<T>(x)), ReturnType<typeof setTimeout> timers, admin-api types reached through mapped types, or are null arguments rather than tests. All are left alone by design.

Checker time on the 209 test entries: no measurable change (587 ms vs 607 ms on main, SAFE_TS_CACHE=0, 5 runs).

Verification

All pass: npm run build, cargo nextest run --workspace (212), cargo clippy -q --workspace --all-targets (nothing new in this code), npm run test:std, npm run typecheck, npm run typecheck:emit, node scripts/docs-typecheck.mjs (388 examples), npm run test:docs, npm run test:vite, npm run bench:check, node scripts/verify-packages.mjs.

New tests:

  • Fixtures null_check (cross-file, barrel re-export, classes, assertions, left-alone cases) and null_outside.
  • Fix tests for every quick fix, and a test that JSON.stringify doesn't report jsonNull / JsonNull.
  • The codemod case for the optional parameter.
  • std tests for JsonNull / RawJson.

🤖 Generated with Claude Code

Round 3 of the 0.2.0 adoption feedback, area **absence and `null`** (top-ten #1 and #9). ## Per feedback item **1. A rule mirroring `no-undefined-check-for-null`: done.** New rule `no-null-check-for-undefined`, in the default set as an error (it reports only where the type is known to have no `null`). It reports: - `=== null`, `!== null`, `== null`, `!= null`; - `null` expected by an assertion: `node:assert` / `node:assert/strict` and chai `equal`, `strictEqual`, `deepEqual`, ... (on the module, imported by name, `assert.strict.*`), also at one element of an array or object literal (`assert.deepEqual([a, b], ["paid", null])`); - chai's `isNull` / `isNotNull`, and vitest/jest `toBe(null)`, `toEqual(null)`, `toStrictEqual(null)`, `toBeNull()`, `.not`. A value counts as "no `null`" when its declared type has none: variables, parameters, destructuring, fields (inherited too, and class fields and parameter properties), return types of the project's functions and methods. It follows imports and re-exports (`export *` too), array elements, `for...of`, element callbacks (`forEach((x) => ...)`), `Map#get`, `Array#find/at/pop`, `await` of a `Promise<Option<T>>`, `??`, `?:`, and the packs' Option safe versions. The per-file part (`null_check.rs`) turns declarations into small shapes; the project pass evaluates them across files. Left alone: anything that may hold `null` or whose type isn't known. That covers DOM lookups (they keep `toBeNull()`), `unknown`/`any`, packages' types, generics (`first<T>(): Option<T>`), `ReturnType<...>`, and conditional and mapped types. Decision on #61's check: the safe-version `=== null` report moved from `no-null` into the new rule (same message wording, *Compare with undefined*), so each message has one rule. Where the new rule reports a loose `== null`, `no-null`'s report of that `null` is dropped, so there are no two reports for one mistake. Quick fixes: *Compare with undefined*, *Use toBeUndefined()*, *Use toBeDefined()* (for `.not.toBeNull()`), chai *Use isUndefined()* / *Use isDefined()*. **2. `parseJson` / `validate` keeping a JSON `null`: done, with types rather than an option.** - `JsonNull`: in a type, only a `null` fits it and the result keeps it. `category: string | JsonNull` refuses a missing key; `category?: string | JsonNull` leaves it out; `Option<T> | JsonNull` gives `undefined` for missing and `null` for `null`. In a dictionary, a `null` value keeps its key. Works in `fromFields` and `arbitrary` too. - `RawJson`: any JSON as `JSON.parse` gives it, every `null` kept, so it comes back byte for byte. It is checked like `JsonValue` (no NaN, class instances or cycles). - The default is unchanged (`null` becomes `undefined`). - `jsonNull` is now typed `JsonNull` and documented as the output-format and raw-JSON escape, not only for tests. `JSON.stringify` of data holding it, or typed with `JsonNull` fields, isn't reported. - No `{ nulls: "keep" }` option: `parseJson<JsonValue>(text, { nulls: "keep" })` would hand back `null`s that its type says can't be there. The type says it instead. - Tests: the discount action (`"category": null` = every category, missing = refused), a canonical hash of settings with `null`s, byte-identical round trips, and arbitrary round trips. **3. `no-null` accepts `null` / `?? null` where a package's or the platform's type is expected: done, except one case it can't see.** This covers the return of a function or arrow declared with such a type (`bound(p): SQLInputValue`, `params.map((p): SQLInputValue => p ?? null)`, async `Promise<T>` too) and `push`/`unshift` into an array declared with such elements. It also covers the elements of such an array literal, a variable declared with such a type, and assignment to a field of a package's object, also for each `child of group.children`. It covers methods of values declared with the platform's type (`gl.texImage2D(..., null)` with `gl: WebGL2RenderingContext`, or `this.#gl`), using #57's global types and excluding containers like `Map`, `Array` and `Record`. Last, the `null` in a `el: HTMLElement | null` parameter is allowed when the parameter only goes to outside code or is tested (compared, read from, `?.`, `if (el)`), and is never returned, stored or passed to the program's own functions. It reuses #46's `package_type`. Not covered: TwitchRTS's actual `c.parent = null`, where `c` comes from a `Set<Container>` in a `Map` value. Without a type checker, nothing declares it there (documented in "What the rule can't see"). **4. The `null-to-undefined` codemod writes `x?: Option<T>`: done.** It does this when every parameter after the one with `= null` may be left out too. Otherwise the default stays (`x: Option<T> = undefined`, the same thing). **5. Docs: done.** **Upgrading notes:** - `exactOptionalPropertyTypes` and `kind: c ? undefined : kind`: a paragraph in the absence guide (write the two objects, or `Option<T>`). - The adoption guide's codemod section now points to the new rule for code merged later. ## Docs pages changed - New: `docs/rules/no-null-check-for-undefined.md`. - Updated: `docs/rules/no-null.md`, `docs/guide/absence.md` ("`null` from outside", comparisons both ways, `JsonNull`, `exactOptionalPropertyTypes`), `docs/guide/json.md` ("Keeping a JSON `null`", replacing "A JSON `null` in test data"), `docs/guide/libraries.md`, `docs/guide/adoption.md`, `docs/guide/testing.md`. - Also updated: `docs/README.md` and `README.md` rule tables and std listing, the docs sidebar, `CHANGELOG.md` (Unreleased: Added and Changed; #61's line now names the new rule). ## TwitchRTS check The branch's own code already carries the hand workarounds, so it has 0 `no-null` and 0 new-rule reports before and after. To measure #1, I took the 199 comparison and assertion lines the adoption commit changed by hand from `null` to `undefined` (`=== null`, `toBeNull`, `assert.equal(x, null)`, ...) and put the `null` forms back in a scratch copy. Results: - main: 0 reports. - This branch: 138 reported, all 138 on those lines, 0 anywhere else. - The 61 not reported go through generic helpers (`defined<T>(x)`), `ReturnType<typeof setTimeout>` timers, admin-api types reached through mapped types, or are `null` arguments rather than tests. All are left alone by design. Checker time on the 209 test entries: no measurable change (587 ms vs 607 ms on main, `SAFE_TS_CACHE=0`, 5 runs). ## Verification All pass: `npm run build`, `cargo nextest run --workspace` (212), `cargo clippy -q --workspace --all-targets` (nothing new in this code), `npm run test:std`, `npm run typecheck`, `npm run typecheck:emit`, `node scripts/docs-typecheck.mjs` (388 examples), `npm run test:docs`, `npm run test:vite`, `npm run bench:check`, `node scripts/verify-packages.mjs`. New tests: - Fixtures `null_check` (cross-file, barrel re-export, classes, assertions, left-alone cases) and `null_outside`. - Fix tests for every quick fix, and a test that `JSON.stringify` doesn't report `jsonNull` / `JsonNull`. - The codemod case for the optional parameter. - std tests for `JsonNull` / `RawJson`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Absence and null: no-null-check-for-undefined, a JSON null kept, no-null at outside types
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m22s
c51b20bba7
- New rule no-null-check-for-undefined (default, error), the mirror of
  no-undefined-check-for-null: `=== null`, `== null`, assertions expecting `null`
  (node:assert, chai, vitest/jest `toBe(null)`, `toBeNull()`, also at an element of
  an array or object literal) on values whose type is known to have no `null`:
  declared Options and `?:` fields across files, return types, Map#get, array
  elements, and the packs' Option safe versions (moved here from no-null). Types
  are read from the declarations (null_check.rs) and evaluated by the project pass.
- std json: `JsonNull` (a JSON null kept as null; only null fits it) and `RawJson`
  (any JSON with every null kept, written back byte for byte); `jsonNull` typed
  `JsonNull`; JSON.stringify of data holding it isn't reported.
- no-null accepts `null` / `?? null` where a package's or the platform's type is
  expected: declared return types, arrays and variables of such types, fields of
  package objects, methods of platform-typed values, and a `T | null` parameter
  that only hands the value on to outside code or tests it.
- null-to-undefined writes `x?: Option<T>` for a trailing parameter defaulting to null.
- Docs: new rule page, absence and JSON guides, no-null, libraries, adoption,
  testing, READMEs, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge remote-tracking branch 'origin/main' into up-63
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m21s
469dbb9dbc
sionzee deleted branch evobug/fb3-absence 2026-11-16 23:46:33 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!63
No description provided.