Skip to content

[restrict-template-expressions] option to ignore for console.log and similar methods #2261

@justingrant

Description

@justingrant

I just upgraded typescript-eslint and got many new restrict-template-expressions warnings, almost all of which were in console.log messages or other similar contexts where the warning was a false positive. In logging code, logging undefined/null as "undefined" or "null" is almost always the expected result, but in normal code the reverse is true.

Therefore, I think this is a useful rule for "normal" code where strings are being constructed for showing to users, but if 99% of the time it's a false positive on log statements then it's hard to justify leaving it active in my projects.

Could typescript-eslint offer a way to automatically ignore this rule when the template strings are being constructed as parameters to console.log? Ideally, I could add a whitelist of other methods (e.g. custom loggers) whose parameters would also be ignored by this rule.

I assume that the hard part would be uniquely identifying methods. IMHO I think it's OK to use dumb regex matching by the name used in the code, e.g. methodName: [/\.log$/, /myCoolLogger/] which puts the onus on developers to add any aliases. A default could be [/\.log$/, [/\.warn$/, [/\.info$/] or maybe just [/console\.$/].

Repro

{
  "rules": {
    "@typescript-eslint/restrict-template-expressions": ["warn", { "allowNumber": true }]
  }
}
const foo = Math.random() < 0.5 ? 1 : undefined;
console.log(`foo is: ${foo}`);

Expected Result
There's some way for me to tell ESLint that some functions like console.log should allow undefined or null values-- if only because a big reason for logging is to report on unusual/unexpected values!

Actual Result

Invalid type "1 | undefined" of template literal expression.
eslint@typescript-eslint/restrict-template-expressions

Additional Info
n/a

Versions

package version
@typescript-eslint/eslint-plugin 3.4.0
@typescript-eslint/parser 3.4.0
TypeScript 3.9.5
ESLint 7.3.1
node 14.4.0
npm 6.14.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement: plugin rule optionNew rule option for an existing eslint-plugin rulepackage: eslint-pluginIssues related to @typescript-eslint/eslint-pluginwontfixThis will not be worked on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions