Skip to main content

restrict-template-expressions

Enforce template literal expressions to be of string type.

Attributes

  • Included in configs
    • ✅ Recommended
    • 🔒 Strict
  • Fixable
    • 🔧 Automated Fixer
    • 🛠 Suggestion Fixer
  • 💭 Requires type information

Rule Details

Examples of code for this rule:

const arg1 = [1, 2];
const msg1 = `arg1 = ${arg1}`;

const arg2 = { name: 'Foo' };
const msg2 = `arg2 = ${arg2 || null}`;

Options

The rule accepts an options object with the following properties:

type Options = {
// if true, also allow number type in template expressions
allowNumber?: boolean;
// if true, also allow boolean type in template expressions
allowBoolean?: boolean;
// if true, also allow any in template expressions
allowAny?: boolean;
// if true, also allow null and undefined in template expressions
allowNullish?: boolean;
// if true, also allow RegExp in template expressions
allowRegExp?: boolean;
};

const defaults = {
allowNumber: true,
allowBoolean: false,
allowAny: false,
allowNullish: false,
allowRegExp: false,
};

allowNumber

Examples of additional correct code for this rule with { allowNumber: true }:

const arg = 123;
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'zero'}`;

allowBoolean

Examples of additional correct code for this rule with { allowBoolean: true }:

const arg = true;
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'not truthy'}`;

allowAny

Examples of additional correct code for this rule with { allowAny: true }:

const user = JSON.parse('{ "name": "foo" }');
const msg1 = `arg = ${user.name}`;
const msg2 = `arg = ${user.name || 'the user with no name'}`;

allowNullish

Examples of additional correct code for this rule with { allowNullish: true }:

const arg = condition ? 'ok' : null;
const msg1 = `arg = ${arg}`;

allowRegExp

Examples of additional correct code for this rule with { allowRegExp: true }:

const arg = new RegExp('foo');
const msg1 = `arg = ${arg}`;
const arg = /foo/;
const msg1 = `arg = ${arg}`;