Skip to content

feat(eslint-plugin): [no-unnecessary-type-conversion] add rule #10182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 41 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
762cd47
add no-unnecessary-coercion rule
Oct 20, 2024
3060bff
resolve no-unnecessary-coercion rule problems in repository
Oct 20, 2024
393fb2f
rename to no-unnecessary-type-conversion
Nov 3, 2024
00476f9
make perfectionist happy
Nov 3, 2024
89ecd74
rename isString to matchesType to accurately reflect that it works wi…
Nov 3, 2024
879dd41
don't pass node to context.report if a loc is already being passed
Nov 3, 2024
1638cb3
improve loc generation for !!, +, and ~~ operators
Nov 3, 2024
0112f0a
don't use messageId constant in tests
Nov 3, 2024
bfd8c5b
retrieve types only when we need to in order to be more performant
Nov 3, 2024
05f4c6e
Merge branch 'real_main'
Jan 19, 2025
e125bb9
PR feedback
Jan 25, 2025
0a1257b
implement satisfies suggestions
Jan 26, 2025
0dd5d52
don't trigger rule if type constructor calls are overriden
Jan 26, 2025
b054d60
put parentheses around satisfies suggestion autofix when parent is a …
Jan 26, 2025
aac5d40
resolve bad autofix for !(!false)
Jan 26, 2025
1029658
Merge branch 'real_main'
Jan 26, 2025
988f383
show satisfies suggestion for member expressions passed to type const…
Jan 26, 2025
606556e
different autofixes for the case where str += '' is used as a stateme…
Jan 26, 2025
6691fc7
Merge branch 'real_main'
Feb 2, 2025
6033707
always provide a satisfies suggestion
Feb 2, 2025
d5b9f2f
fix minor grammar mistakes in getWrappingFixer
Feb 2, 2025
7568840
make satisfies suggestion fixes use getWrappingFixer
Feb 2, 2025
251bb05
resolve issue where satisfies suggestion for unary operators gives li…
Feb 2, 2025
0b12c0e
make autofixes use getWrappingFixer
Feb 2, 2025
c85bf9a
add suggestions to all tests
Feb 2, 2025
2877d5f
basic implementation of optional wrap parameter to getWrappingFixer
Feb 2, 2025
178b961
remove code path that doesn't seem to be possible to hit
Feb 2, 2025
a89e6ca
Merge branch 'real_main'
Mar 23, 2025
74bf8a1
add tests based on feedback
Mar 24, 2025
17dfbc9
change all autofixes to suggestions
Apr 5, 2025
6afafe9
change getType to getTypeLazy
Apr 5, 2025
c0976d1
alias node callee to avoid type assertion
Apr 5, 2025
973234f
fix type in message
Apr 5, 2025
e8956c0
use unionTypeParts helper function
Apr 5, 2025
ad88ade
make handleUnaryOperator cleaner
Apr 5, 2025
36cf822
Merge branch 'real_main'
Apr 5, 2025
8539069
fix test after main merge
Apr 5, 2025
2a1471f
Merge branch 'real_main'
Apr 13, 2025
4a56a42
Merge branch 'real_main'
Apr 15, 2025
94ebd1e
update snapshots
Apr 15, 2025
0d16798
Merge branch 'main' into main
skondrashov Apr 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export default tseslint.config(
'error',
{ allowConstantLoopConditions: true, checkTypePredicates: true },
],
'@typescript-eslint/no-unnecessary-type-conversion': 'error',
'@typescript-eslint/no-unnecessary-type-parameters': 'error',
'@typescript-eslint/no-unused-expressions': 'error',
'@typescript-eslint/no-unused-vars': [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
description: 'Disallow conversion idioms when they do not change the type or value of the expression.'
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/no-unnecessary-type-conversion** for documentation.

JavaScript has several idioms used to convert values to certain types. With TypeScript, it is possible to see at build time if the value is already of that type, making the conversion unnecessary.
Performing unnecessary conversions increases visual clutter and harms code readability, so it's generally best practice to remove them if they don't change the type of an expression.
This rule reports when a type conversion idiom is identified which does not change the type of an expression.

## Examples

<Tabs>
<TabItem value="❌ Incorrect">

```ts
String('123');
'123'.toString();
'' + '123';
'123' + '';

Number(123);
+123;
~~123;

Boolean(true);
!!true;

BigInt(BigInt(1));

let str = '123';
str += '';
```

</TabItem>
<TabItem value="✅ Correct">

```ts
function foo(bar: string | number) {
String(bar);
bar.toString();
'' + bar;
bar + '';

Number(bar);
+bar;
~~bar;

Boolean(bar);
!!bar;

BigInt(1);

bar += '';
}
```

</TabItem>
</Tabs>

## When Not To Use It

If you don't care about having no-op type conversions in your code, then you can turn off this rule.
If you have types which are not accurate, then this rule might cause you to remove conversions that you actually do need.

## Related To

- [no-unnecessary-type-assertion](./no-unnecessary-type-assertion.mdx)
- [no-useless-template-literals](./no-useless-template-literals.mdx)
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/eslintrc/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export = {
'@typescript-eslint/no-unnecessary-type-arguments': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unnecessary-type-conversion': 'error',
'@typescript-eslint/no-unnecessary-type-parameters': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export = {
'@typescript-eslint/no-unnecessary-template-expression': 'off',
'@typescript-eslint/no-unnecessary-type-arguments': 'off',
'@typescript-eslint/no-unnecessary-type-assertion': 'off',
'@typescript-eslint/no-unnecessary-type-conversion': 'off',
'@typescript-eslint/no-unnecessary-type-parameters': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/flat/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export default (
'@typescript-eslint/no-unnecessary-type-arguments': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unnecessary-type-conversion': 'error',
'@typescript-eslint/no-unnecessary-type-parameters': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export default (
'@typescript-eslint/no-unnecessary-template-expression': 'off',
'@typescript-eslint/no-unnecessary-type-arguments': 'off',
'@typescript-eslint/no-unnecessary-type-assertion': 'off',
'@typescript-eslint/no-unnecessary-type-conversion': 'off',
'@typescript-eslint/no-unnecessary-type-parameters': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export default createRule({
return {
...getNameFromMember(member, context.sourceCode),
callSignature: false,
static: !!member.static,
static: member.static,
};
case AST_NODE_TYPES.TSCallSignatureDeclaration:
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,14 @@ export default createRule<Options, MessageIds>({
}
}
}
if (!!funcName && !!options.allowedNames.includes(funcName)) {
if (!!funcName && options.allowedNames.includes(funcName)) {
return true;
}
}
if (
node.type === AST_NODE_TYPES.FunctionDeclaration &&
node.id &&
!!options.allowedNames.includes(node.id.name)
options.allowedNames.includes(node.id.name)
) {
return true;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ import noUnnecessaryTemplateExpression from './no-unnecessary-template-expressio
import noUnnecessaryTypeArguments from './no-unnecessary-type-arguments';
import noUnnecessaryTypeAssertion from './no-unnecessary-type-assertion';
import noUnnecessaryTypeConstraint from './no-unnecessary-type-constraint';
import noUnnecessaryTypeConversion from './no-unnecessary-type-conversion';
import noUnnecessaryTypeParameters from './no-unnecessary-type-parameters';
import noUnsafeArgument from './no-unsafe-argument';
import noUnsafeAssignment from './no-unsafe-assignment';
Expand Down Expand Up @@ -208,6 +209,7 @@ const rules = {
'no-unnecessary-type-arguments': noUnnecessaryTypeArguments,
'no-unnecessary-type-assertion': noUnnecessaryTypeAssertion,
'no-unnecessary-type-constraint': noUnnecessaryTypeConstraint,
'no-unnecessary-type-conversion': noUnnecessaryTypeConversion,
'no-unnecessary-type-parameters': noUnnecessaryTypeParameters,
'no-unsafe-argument': noUnsafeArgument,
'no-unsafe-assignment': noUnsafeAssignment,
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/rules/member-ordering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ function isMemberOptional(node: Member): boolean {
case AST_NODE_TYPES.PropertyDefinition:
case AST_NODE_TYPES.TSAbstractMethodDefinition:
case AST_NODE_TYPES.MethodDefinition:
return !!node.optional;
return node.optional;
}
return false;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/eslint-plugin/src/rules/no-duplicate-enum-values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ export default createRule({

let value: number | string | undefined;
if (isStringLiteral(member.initializer)) {
value = String(member.initializer.value);
value = member.initializer.value;
} else if (isNumberLiteral(member.initializer)) {
value = Number(member.initializer.value);
value = member.initializer.value;
} else if (isStaticTemplateLiteral(member.initializer)) {
value = member.initializer.quasis[0].value.cooked;
}
Expand Down
5 changes: 2 additions & 3 deletions packages/eslint-plugin/src/rules/no-empty-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,10 @@ export default createRule<Options, MessageIds>({
def => def.node.type === AST_NODE_TYPES.ClassDeclaration,
);

const isInAmbientDeclaration = !!(
const isInAmbientDeclaration =
isDefinitionFile(context.filename) &&
scope.type === ScopeType.tsModule &&
scope.block.declare
);
scope.block.declare;

const useAutoFix = !(
isInAmbientDeclaration || mergedWithClassDeclaration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ function describeLiteralTypeNode(typeNode: TSESTree.TypeNode): string {
}

function isNodeInsideReturnType(node: TSESTree.TSUnionType): boolean {
return !!(
return (
node.parent.type === AST_NODE_TYPES.TSTypeAnnotation &&
isFunctionOrFunctionType(node.parent.parent)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ const evenNumOfBackslashesRegExp = /(?<!(?:[^\\]|^)(?:\\\\)*\\)/;
// '\\\\$' <- true
// '\\\\\\$' <- false
function endsWithUnescapedDollarSign(str: string): boolean {
return new RegExp(`${String(evenNumOfBackslashesRegExp.source)}\\$$`).test(
str,
);
return new RegExp(`${evenNumOfBackslashesRegExp.source}\\$$`).test(str);
}

export default createRule<[], MessageId>({
Expand Down Expand Up @@ -316,10 +314,7 @@ export default createRule<[], MessageId>({
// \${ -> \${
// \\${ -> \\\${
.replaceAll(
new RegExp(
`${String(evenNumOfBackslashesRegExp.source)}(\`|\\\${)`,
'g',
),
new RegExp(`${evenNumOfBackslashesRegExp.source}(\`|\\\${)`, 'g'),
'\\$1',
);

Expand Down
Loading