Skip to content

Instantly share code, notes, and snippets.

@nicholaswmin
Last active August 4, 2016 19:21
Show Gist options
  • Save nicholaswmin/d705fd3cca65d9a2d4fe6284da0af7be to your computer and use it in GitHub Desktop.
Save nicholaswmin/d705fd3cca65d9a2d4fe6284da0af7be to your computer and use it in GitHub Desktop.
Type preservation in ES6 String Interpolation/Template Literlars
/*
* 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