Skip to content

Require Safety Comment for Type Assertion

Error
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) 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.

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 typescript/no-unsafe-type-assertion` directive 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.

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

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;