JavaScript

JavaScript

By DeepSource

Found template literal expression having a non-string type JS-0378

Anti-pattern

Using only string values in placeholders is recommended as otherwise, the value may be wrongly displayed; for example, if an object value is directly included in a string, it will be shown as [object Object]. Using only string values can also ensure that null or undefined values are not directly displayed.

A placeholder is represented by ${}, with anything within the curly brackets treated as an executable JavaScript expression and anything outside the brackets treated as a string. To avoid unwanted implicit string coercions like [object Object], we can explicitly add a toString() call to the end of the expression, as shown below:

console.log(`${o.toString()} <- is ok`)
// [object Object] <- is ok

Examples

Bad Practice

const arg1 = [1, 2];
const msg1 = `arg1 = ${arg1}`;
const arg2 = { name: 'DeepSource' };
const msg2 = `arg2 = ${arg2 || null}`;

Recommended

const arg = 'DeepSource';
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'default'}`;

const stringWithKindProp: string & { _kind?: 'MyString' } = 'DeepSource';
const msg3 = `stringWithKindProp = ${stringWithKindProp}`;