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

Disallow converting a value to the type it already has

has suggestionsneeds types

Also called typescript-eslint/no-unnecessary-type-conversion, typescript/no-unnecessary-type-conversion

String(name), +count and !!isOpen all convert a value. If name is already a string, count is already a number and isOpen is already a boolean, they convert nothing, and the reader is left wondering what else the value could have been.

ReportedIf the value is already
String(x), x.toString(), x + "", "" + x, x += ""a string
Number(x), +xa number
Boolean(x), !!xa boolean
BigInt(x)a bigint
~~xan integer literal type, such as 3

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-conversion" = "error" # or "warn"

Examples#

example.ts4 problems
function format(name: string, count: number, isOpen: boolean) {
  const label = String(name);
  const title = name.toString() + ":";
  const total = +count;
  const open = !!isOpen;
  return [label, title, total, open];
}
example.tsNo problems
function format(name: string, count: number, isOpen: boolean) {
  const label = name;
  const total = count;
  const open = isOpen;
  return [label, total, open];
}

A conversion that changes the type isn't reported:

example.tsNo problems
function read(input: string, id: number | string, user?: object) {
  const count = Number(input);
  const key = String(id);
  const isKnown = !!user;
  return [count, key, isKnown];
}