Skip to content

feat(eslint-plugin): [no-base-to-string] check Array.prototype.join #10287

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
Nov 24, 2024
Merged
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
3 changes: 3 additions & 0 deletions packages/eslint-plugin/docs/rules/no-base-to-string.mdx
Original file line number Diff line number Diff line change
@@ -34,6 +34,9 @@ value + '';
String({});
({}).toString();
({}).toLocaleString();

// Stringifying objects or instances in an array with the `Array.prototype.join`.
[{}, new MyClass()].join('');
```

</TabItem>
143 changes: 106 additions & 37 deletions packages/eslint-plugin/src/rules/no-base-to-string.ts
Original file line number Diff line number Diff line change
@@ -2,9 +2,16 @@
import type { TSESTree } from '@typescript-eslint/utils';

import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as tsutils from 'ts-api-utils';
import * as ts from 'typescript';

import { createRule, getParserServices, getTypeName } from '../util';
import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
getTypeName,
nullThrows,
} from '../util';

enum Usefulness {
Always = 'always',
@@ -17,7 +24,7 @@ type Options = [
ignoredTypeNames?: string[];
},
];
type MessageIds = 'baseToString';
type MessageIds = 'baseArrayJoin' | 'baseToString';

export default createRule<Options, MessageIds>({
name: 'no-base-to-string',
@@ -30,6 +37,8 @@ export default createRule<Options, MessageIds>({
requiresTypeChecking: true,
},
messages: {
baseArrayJoin:
"Using `join()` for {{name}} {{certainty}} use Object's default stringification format ('[object Object]') when stringified.",
baseToString:
"'{{name}}' {{certainty}} use Object's default stringification format ('[object Object]') when stringified.",
},
@@ -64,7 +73,6 @@ export default createRule<Options, MessageIds>({
if (node.type === AST_NODE_TYPES.Literal) {
return;
}

const certainty = collectToStringCertainty(
type ?? services.getTypeAtLocation(node),
);
@@ -82,6 +90,91 @@ export default createRule<Options, MessageIds>({
});
}

function checkExpressionForArrayJoin(
node: TSESTree.Node,
type: ts.Type,
): void {
const certainty = collectJoinCertainty(type);

if (certainty === Usefulness.Always) {
return;
}

context.report({
node,
messageId: 'baseArrayJoin',
data: {
name: context.sourceCode.getText(node),
certainty,
},
});
}

function collectUnionTypeCertainty(
type: ts.UnionType,
collectSubTypeCertainty: (type: ts.Type) => Usefulness,
): Usefulness {
const certainties = type.types.map(t => collectSubTypeCertainty(t));
if (certainties.every(certainty => certainty === Usefulness.Never)) {
return Usefulness.Never;
}

if (certainties.every(certainty => certainty === Usefulness.Always)) {
return Usefulness.Always;
}

return Usefulness.Sometimes;
}

function collectIntersectionTypeCertainty(
type: ts.IntersectionType,
collectSubTypeCertainty: (type: ts.Type) => Usefulness,
): Usefulness {
for (const subType of type.types) {
const subtypeUsefulness = collectSubTypeCertainty(subType);

if (subtypeUsefulness === Usefulness.Always) {
return Usefulness.Always;
}
}

return Usefulness.Never;
}

function collectJoinCertainty(type: ts.Type): Usefulness {
if (tsutils.isUnionType(type)) {
return collectUnionTypeCertainty(type, collectJoinCertainty);
}

if (tsutils.isIntersectionType(type)) {
return collectIntersectionTypeCertainty(type, collectJoinCertainty);
}

if (checker.isTupleType(type)) {
const typeArgs = checker.getTypeArguments(type);
const certainties = typeArgs.map(t => collectToStringCertainty(t));
if (certainties.some(certainty => certainty === Usefulness.Never)) {
return Usefulness.Never;
}

if (certainties.some(certainty => certainty === Usefulness.Sometimes)) {
return Usefulness.Sometimes;
}

return Usefulness.Always;
}

if (checker.isArrayType(type)) {
const elemType = nullThrows(
type.getNumberIndexType(),
'array should have number index type',
);
return collectToStringCertainty(elemType);
}

return Usefulness.Always;
}

function collectToStringCertainty(type: ts.Type): Usefulness {
const toString =
checker.getPropertyOfType(type, 'toString') ??
@@ -113,45 +206,13 @@ export default createRule<Options, MessageIds>({
}

if (type.isIntersection()) {
for (const subType of type.types) {
const subtypeUsefulness = collectToStringCertainty(subType);

if (subtypeUsefulness === Usefulness.Always) {
return Usefulness.Always;
}
}

return Usefulness.Never;
return collectIntersectionTypeCertainty(type, collectToStringCertainty);
}

if (!type.isUnion()) {
return Usefulness.Never;
}

let allSubtypesUseful = true;
let someSubtypeUseful = false;

for (const subType of type.types) {
const subtypeUsefulness = collectToStringCertainty(subType);

if (subtypeUsefulness !== Usefulness.Always && allSubtypesUseful) {
allSubtypesUseful = false;
}

if (subtypeUsefulness !== Usefulness.Never && !someSubtypeUseful) {
someSubtypeUseful = true;
}
}

if (allSubtypesUseful && someSubtypeUseful) {
return Usefulness.Always;
}

if (someSubtypeUseful) {
return Usefulness.Sometimes;
}

return Usefulness.Never;
return collectUnionTypeCertainty(type, collectToStringCertainty);
}

function isBuiltInStringCall(node: TSESTree.CallExpression): boolean {
@@ -188,12 +249,20 @@ export default createRule<Options, MessageIds>({
checkExpression(node.arguments[0]);
}
},
'CallExpression > MemberExpression.callee > Identifier[name = "join"].property'(
node: TSESTree.Expression,
): void {
const memberExpr = node.parent as TSESTree.MemberExpression;
const type = getConstrainedTypeAtLocation(services, memberExpr.object);
checkExpressionForArrayJoin(memberExpr.object, type);
},
'CallExpression > MemberExpression.callee > Identifier[name = /^(toLocaleString|toString)$/].property'(
node: TSESTree.Expression,
): void {
const memberExpr = node.parent as TSESTree.MemberExpression;
checkExpression(memberExpr.object);
},

TemplateLiteral(node: TSESTree.TemplateLiteral): void {
if (node.parent.type === AST_NODE_TYPES.TaggedTemplateExpression) {
return;

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

Loading