-->

Detecting template literals in javascript

2019-08-23 22:53发布

问题:

We have two potential values:

const value = `Hello World`;

and

const value = {message: 'Hello World'};

What I'm trying to do is a conditional where

if(is template literal) {
    // Some code
} else {
    // Some code
}

I've tried using

if(String.raw(value)){

} else {

}

But the object throws a type error. Does anyone have an easy reliable way to detect template literals in javascript?

Edit: Here is some further clarification for those who are asking.

const exampleFunc = (value) => {
    // If I pass a string or template literal return as is
    if (String.raw({raw: value})) return value;

    const css = arr(styles).reduce((acc, obj) => {
        // Passing an object handles a more complicated set of operations
    }

}

Before I was using if (String.raw(value)) return value;

And what was happening here is it was giving me a type error rather than handing me null. By passing {raw: value} to String.raw instead solved the problem and I can now detect whether its a string/template literal or an object.

The clarifications to why I'm doing it this way is a longer story that has to do with React & styled components.

回答1:

There is no difference between using a string literal and a template literal (except, obviously, on the source code level).

But your first value is a string, while the second one is an object, and those are easy to distinguish:

if (typeof value == "string") {
    console.log(value)
} else if (typeof value == "object" && typeof value.message == "string") {
    console.log(value.message)
}