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}`;
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/restrict-template-expressions": "error"
}
};

Options

This rule accepts an options object with the following properties:

interface Options {
/**
* Whether to allow `number` typed values in template expressions.
*/
allowNumber?: boolean;
/**
* Whether to allow `boolean` typed values in template expressions.
*/
allowBoolean?: boolean;
/**
* Whether to allow `any` typed values in template expressions.
*/
allowAny?: boolean;
/**
* Whether to allow `nullish` typed values in template expressions.
*/
allowNullish?: boolean;
/**
* Whether to allow `regexp` typed values in template expressions.
*/
allowRegExp?: boolean;
}

const defaultOptions: Options = [{ allowNumber: true }];

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}`;

Resources