@typescript-eslint/no-unnecessary-type-assertion
Disallow as, <T> and ! assertions that do not change the type
Also called typescript-eslint/no-unnecessary-type-assertion, typescript/no-unnecessary-type-assertion
An assertion tells the compiler "trust me". If the expression already has that type, or the place that receives it accepts the original type, the assertion does nothing today. But it stays in the code and silences the compiler when the types change later.
--fix removes the assertion.
bun lint --type-aware turns this rule on in TypeScript files.
Configure#
Off by default. This rule needs types, so turning it on makes bun lint type check your code first.
[lint.rules]
"@typescript-eslint/no-unnecessary-type-assertion" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"@typescript-eslint/no-unnecessary-type-assertion" = ["error", {
checkLiteralConstAssertions = false,
typesToIgnore = [], # list of strings
}]Examples#
interface User {
name: string;
email?: string;
}
function show(user: User) {
const name = user.name as stringThis assertion is unnecessary since it does not change the type of the expression.;
const length = user.name!This assertion is unnecessary since it does not change the type of the expression..length;
const email: string | undefined = user.email!This assertion is unnecessary since the receiver accepts the original type of the expression.;
return [name, length, email];
}interface User {
name: string;
email?: string;
}
function show(user: User) {
const name = user.name;
const length = user.name.length;
const email: string = user.email!;
return [name, length, email];
}An assertion that narrows or widens the type isn't reported:
function parse(text: string) {
const data = JSON.parse(text) as { id: number };
let mode = "dark" as "dark" | "light";
return [data, mode];
}Options#
| Option | Default | What it does |
|---|---|---|
checkLiteralConstAssertions | false | Also report as const on a literal in a const declaration, where the type is already the literal type. |
typesToIgnore | [] | Type names, as written after as. Assertions to these types are never reported. |
Reported only with checkLiteralConstAssertions:
{ "checkLiteralConstAssertions": true }1 problemconst retries = 3 as constThis assertion is unnecessary since it does not change the type of the expression.;Not reported with "typesToIgnore": ["UserId"]:
{ "typesToIgnore": ["UserId"] }No problemstype UserId = string;
function key(id: UserId) {
return id as UserId;
}