restrict-template-expressions
Enforce template literal expressions to be of
string
type.
Extending "plugin:@typescript-eslint/recommended-requiring-type-checking"
in an ESLint configuration enables this rule.
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 values used in a template literal string that aren't primitives and don't define a more useful .toString()
method.
module.exports = {
"rules": {
"@typescript-eslint/restrict-template-expressions": "error"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
const arg1 = [1, 2];
const msg1 = `arg1 = ${arg1}`;
const arg2 = { name: 'Foo' };
const msg2 = `arg2 = ${arg2 || null}`;
const arg = 'foo';
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'default'}`;
const stringWithKindProp: string & { _kind?: 'MyString' } = 'foo';
const msg3 = `stringWithKindProp = ${stringWithKindProp}`;
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 }];
Options
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}`;