Skip to content

Require Safety Comment for Type Assertion

UpdatedError
small-rules/require-safety-comment-for-type-assertion

Require a nearby safety-marker comment (or a described Oxlint suppression of typescript/no-unsafe-type-assertion or another configured rule) for every TypeScript type assertion except const assertions.

Rationale

Ported from dmmulroy/anti-slop. A cast is an unchecked claim. A nearby SAFETY: comment records the invariant that makes that claim legitimate; as const is exempt because it doesn’t claim an unrelated runtime shape.

A comment that turns off typescript/no-unsafe-type-assertion also counts as justification, so you don’t write the same sentence twice. That only works when the comment actually covers the diagnostic. oxlint-tsgolint@7.0.2002 narrowed the report onto the as Type syntax, so a disable-next-line on the line preceding a multi-line object does nothing while the as still fails. Tell the rule which world you’re in with {'settings["small-rules"].tsgolintVersion'}. If you omit it, the lookup checks node_modules/oxlint-tsgolint and pnpm-workspace.yaml. It also checks package.json.

A described disable of typescript/no-unsafe-enum-assignment counts too, since that rule also flags a cast to an enum type. To count other rules, list their IDs in the suppressionRules option. The option replaces the default list (typescript/no-unsafe-type-assertion and typescript/no-unsafe-enum-assignment), so repeat the ones you still want.

Diagnostic Messages

missingSafetyComment
This type assertion has no `{{marker}}:` justification. State the checked invariant immediately before the assertion or its containing statement, or add a described `oxlint-disable-next-line` / `oxlint-disable-line` directive for a rule listed in `suppressionRules` (default `typescript/no-unsafe-type-assertion`) that covers the assertion.

Configuration

This rule accepts one options object after the severity.

markersOptional

Comment markers that introduce a justification, written as MARKER: followed by non-whitespace text.

suppressionRulesOptional

Rule IDs whose described oxlint-disable directive counts as justification for a type assertion. Replaces the default list.

{
"jsPlugins": [
"@pobammer-ts/small-rules"
],
"rules": {
"small-rules/require-safety-comment-for-type-assertion": [
"error",
{
"markers": [
"SAFETY"
],
"suppressionRules": [
"typescript/no-unsafe-type-assertion",
"typescript/no-unsafe-enum-assignment"
]
}
]
}
}

Examples

unexplained type assertion
const userId = value as UserId;
assertion with checked invariant
// SAFETY: parseUserId validated the identifier before branding it.
const userId = value as UserId;