@typescript-eslint/no-unnecessary-type-assertion

Disallow as, <T> and ! assertions that do not change the type

fixableneeds types

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.

bunfig.toml
[lint.rules]
"@typescript-eslint/no-unnecessary-type-assertion" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"@typescript-eslint/no-unnecessary-type-assertion" = ["error", {
  checkLiteralConstAssertions = false,
  typesToIgnore = [], # list of strings
}]

Examples#

example.ts3 problems
interface User {
  name: string;
  email?: string;
}

function show(user: User) {
  const name = user.name as string;
  const length = user.name!.length;
  const email: string | undefined = user.email!;
  return [name, length, email];
}
example.tsNo problems
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:

example.tsNo problems
function parse(text: string) {
  const data = JSON.parse(text) as { id: number };
  let mode = "dark" as "dark" | "light";
  return [data, mode];
}

Options#

OptionDefaultWhat it does
checkLiteralConstAssertionsfalseAlso 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:

example.tswith { "checkLiteralConstAssertions": true }1 problem
const retries = 3 as const;

Not reported with "typesToIgnore": ["UserId"]:

example.tswith { "typesToIgnore": ["UserId"] }No problems
type UserId = string;

function key(id: UserId) {
  return id as UserId;
}