Skip to content

feat(eslint-plugin): [no-base-to-string] handle String() #10005

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

Merged
merged 8 commits into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 13 additions & 1 deletion packages/eslint-plugin/docs/rules/no-base-to-string.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import TabItem from '@theme/TabItem';
>
> See **https://typescript-eslint.io/rules/no-base-to-string** for documentation.

JavaScript will call `toString()` on an object when it is converted to a string, such as when `+` adding to a string or in `${}` template literals.
JavaScript will call `toString()` on an object when it is converted to a string, such as when concatenated with a string (`expr + ''`), when interpolated into template literals (`${expr}`), or when passed as an argument to the String constructor (`String(expr)`).
The default Object `.toString()` and `toLocaleString()` use the format `"[object Object]"`, which is often not what was intended.
This rule reports on stringified values that aren't primitives and don't define a more useful `.toString()` or `toLocaleString()` method.

Expand All @@ -31,6 +31,7 @@ value + '';

// Interpolation and manual .toString() and `toLocaleString()` calls too:
`Value: ${value}`;
String({});
({}).toString();
({}).toLocaleString();
```
Expand All @@ -44,6 +45,7 @@ value + '';
`Value: ${123}`;
`Arrays too: ${[1, 2, 3]}`;
(() => {}).toString();
String(42);
(() => {}).toLocaleString();

// Defining a custom .toString class is considered acceptable
Expand All @@ -64,6 +66,15 @@ const literalWithToString = {
</TabItem>
</Tabs>

## Alternatives

Consider using `JSON.stringify` when you want to convert non-primitive things to string for logging, debugging, etc.

```typescript
declare const o: object;
const errorMessage = 'Found unexpected value: ' + JSON.stringify(o);
```

## Options

### `ignoredTypeNames`
Expand All @@ -82,6 +93,7 @@ The following patterns are considered correct with the default options `{ ignore
let value = /regex/;
value.toString();
let text = `${value}`;
String(/regex/);
```

## When Not To Use It
Expand Down
21 changes: 20 additions & 1 deletion packages/eslint-plugin/src/rules/no-base-to-string.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/internal/prefer-ast-types-enum */
import type { TSESTree } from '@typescript-eslint/utils';

import { AST_NODE_TYPES } from '@typescript-eslint/utils';
Expand Down Expand Up @@ -59,7 +60,7 @@ export default createRule<Options, MessageIds>({
const checker = services.program.getTypeChecker();
const ignoredTypeNames = option.ignoredTypeNames ?? [];

function checkExpression(node: TSESTree.Expression, type?: ts.Type): void {
function checkExpression(node: TSESTree.Node, type?: ts.Type): void {
if (node.type === AST_NODE_TYPES.Literal) {
return;
}
Expand Down Expand Up @@ -153,6 +154,19 @@ export default createRule<Options, MessageIds>({
return Usefulness.Never;
}

function isBuiltInStringCall(node: TSESTree.CallExpression): boolean {
if (
node.callee.type === AST_NODE_TYPES.Identifier &&
node.callee.name === 'String' &&
node.arguments[0]
) {
const scope = context.sourceCode.getScope(node);
const variable = scope.set.get('String');
return !variable?.defs.length;
}
return false;
}

return {
'AssignmentExpression[operator = "+="], BinaryExpression[operator = "+"]'(
node: TSESTree.AssignmentExpression | TSESTree.BinaryExpression,
Expand All @@ -169,6 +183,11 @@ export default createRule<Options, MessageIds>({
checkExpression(node.left, leftType);
}
},
CallExpression(node: TSESTree.CallExpression): void {
if (isBuiltInStringCall(node)) {
checkExpression(node.arguments[0]);
}
},
'CallExpression > MemberExpression.callee > Identifier[name = /^(toLocaleString|toString)$/].property'(
node: TSESTree.Expression,
): void {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 51 additions & 0 deletions packages/eslint-plugin/tests/rules/no-base-to-string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ ruleTester.run('no-base-to-string', rule, {
`,
),

// String()
...literalList.map(i => `String(${i});`),
`
function someFunction() {}
someFunction.toString();
Expand Down Expand Up @@ -132,6 +134,28 @@ tag\`\${{}}\`;
"'' += new Error();",
"'' += new URL();",
"'' += new URLSearchParams();",
`
let numbers = [1, 2, 3];
String(...a);
`,
`
Number(1);
`,
{
code: 'String(/regex/);',
options: [{ ignoredTypeNames: ['RegExp'] }],
},
`
function String(value) {
return value;
}
declare const myValue: object;
String(myValue);
`,
`
import { String } from 'foo';
String({});
`,
],
invalid: [
{
Expand Down Expand Up @@ -182,6 +206,33 @@ tag\`\${{}}\`;
},
],
},
{
code: 'String({});',
errors: [
{
data: {
certainty: 'will',
name: '{}',
},
messageId: 'baseToString',
},
],
},
{
code: `
let objects = [{}, {}];
String(...objects);
`,
errors: [
{
data: {
certainty: 'will',
name: '...objects',
},
messageId: 'baseToString',
},
],
},
{
code: "'' += {};",
errors: [
Expand Down
Loading