0

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
    `value1` is an string, `value2` is an object, `value2.message` is an string; there is no difference between `value1` and `value2.message`at runtime. – PA. Nov 12 '17 at 17:38
  • @PA. Considering that JS is not a compiled language, I don't think that's strictly true. @user3591425: If you change that to `String.raw({raw: value})` it should work, although it will return a value for both string literals and template literals – user184994 Nov 12 '17 at 17:47
  • @user184994 No, that does not work. Btw, there is no clear-cut distinction between interpreting and jit-compiling engines - and javascript is [just a language](https://stackoverflow.com/a/3265680/1048572). – Bergi Nov 12 '17 at 17:53
  • @user184994 got it! it works. thank you! –  Nov 12 '17 at 18:28
  • @user184994 It's not really clear what you're saying with that suggestion. In what way does that work? Why not just check `typeof value === "string"`? – loganfsmyth Nov 12 '17 at 18:46

1 Answers1

3

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)
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375