@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.
| Reported | If the value is already |
|---|---|
String(x), x.toString(), x + "", "" + x, x += "" | a string |
Number(x), +x | a number |
Boolean(x), !!x | a boolean |
BigInt(x) | a bigint |
~~x | an 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 = StringPassing a string to String() does not change the type or value of the string.(name);
const title = name.toString()Calling a string's .toString() method does not change the type or value of the string. + ":";
const total = +Using the unary + operator on a number does not change the type or value of the number.count;
const open = !!Using !! on a boolean does not change the type or value of the boolean.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];
}