Skip to main content

no-base-to-string

Require .toString() to only be called on objects which provide useful information when stringified.

💭

This rule requires type information to run.

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. The default Object .toString() returns "[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() method.

Note that Function provides its own .toString() that returns the function's code. Functions are not flagged by this rule.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-base-to-string": "error"
}
};

Try this rule in the playground ↗

Examples

// Passing an object or class instance to string concatenation:
'' + {};

class MyClass {}
const value = new MyClass();
value + '';

// Interpolation and manual .toString() calls too:
`Value: ${value}`;
({}).toString();
Open in Playground

Options

This rule accepts the following options:

type Options = [
{
ignoredTypeNames?: string[];
},
];

const defaultOptions: Options = [
{ ignoredTypeNames: ['Error', 'RegExp', 'URL', 'URLSearchParams'] },
];

ignoredTypeNames

A string array of type names to ignore, this is useful for types missing toString() (but actually has toString()). There are some types missing toString() in old version TypeScript, like RegExp, URL, URLSearchParams etc.

The following patterns are considered correct with the default options { ignoredTypeNames: ["RegExp"] }:

`${/regex/}`;
'' + /regex/;
/regex/.toString();
let value = /regex/;
value.toString();
let text = `${value}`;
Open in Playground

When Not To Use It

If you don't mind a risk of "[object Object]" or incorrect type coercions in your values, then you will not need this rule.

Further Reading


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting. See Performance Troubleshooting if you experience performance degredations after enabling type checked rules.

Resources