let num = 1
let st = 'data'
console.log(typeof `${num}`, typeof `${st}`)

the output of the first variable should be number but it's printing string when I am using string interpolation console.log(typeof `${num}`) it's printing string, but when I am writing console.log(typeof num) it's printing number can someone plz expalin why

3

There are 3 best solutions below

0
Barmar On

The result of string interpolation (called a template literal) is by definition a string, so that's what typeof returns. The type of the original expression that was interpolated is not available. Usually you're not just putting one expression into the template, there will be multiple expression and/or other text, so it wouldn't even be meaningful for the type to come from the interpolated expression. E.g. if you did

console.log(typeof `num = ${num}, st = ${st}`);

why would you expect the result to be related to the types of num or st?

0
exax On

The backtick converts your number into a string. If you are deadset on using backticks, you can implicitly cast it back to a number like so:

console.log(typeof +`${num}`);

One of the few use cases I'd see for this is if you got number variables as different digits. Example:

// Compose the number "57" and print the type
const tensDigit = 5;
const onesDigit = 7;
console.log(typeof +`${tensDigit}${onesDigit}`)
0
Michal Miky Jankovský On

this is probably what you want:

let num = 1
let st = 'data'
console.log(`typeof num = ${typeof num}, typeof st = ${typeof st}`)

typeof must be followed directly with the variable

template literal always return string and call .toString() method on each variable used in it in ${} thats why after interpolation it is always the string