Last active
August 4, 2016 19:21
-
-
Save nicholaswmin/d705fd3cca65d9a2d4fe6284da0af7be to your computer and use it in GitHub Desktop.
Type preservation in ES6 String Interpolation/Template Literlars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Preservation of implicit type in interpolated string (ES2015) | |
* | |
* Authors: | |
* - Nik Kyriakides, @nicholaswmin, nik.kyriakides@gmail.com | |
* | |
* MIT Licensed | |
*/ | |
const aNum = 3; | |
const aStr = "3"; | |
const typeDeterminant = function(val) { | |
switch (typeof val) { | |
case "string": | |
return `'${val}'`; | |
break; | |
case "number": | |
return val; | |
break; | |
default: | |
return val; | |
} | |
} | |
const interpolated = `Your value: ${typeDeterminant(aStr)}` | |
// prints "Your value: '3'" instead of "Your value: 3" thus implicitly preserving the type | |
console.log(interpolated) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment