Skip to content Skip to sidebar Skip to footer

How Can I Cast A Variable To The Type Of Another In Javascript

I want to be able to cast a variable to the specific type of another. As an example: function convertToType(typevar, var) { return (type typevar)var; // I know this doesn't wor

Solution 1:

function convertToType (t, e) {
    return (t.constructor) (e);
}

repl demo

note the first call when we wanted to convert 15 to a Number, we append a dot (.) to the first parameter

Solution 2:

UPDATE: here's an even more complete example, with tests (requires Node 6+ or some transpilation to ES5): https://github.com/JaKXz/type-convert

You can use the typeof operator to get the right "casting" function:

functionconvertToTypeOf(typedVar, input) {
  return {
    'string': String.bind(null, input),
    'number': Number.bind(null, input)
    //etc
  }[typeof typedVar]();
}

Try it out here: http://jsbin.com/kasomufucu/edit?js,console

I would also suggest looking into TypeScript for your project.

Solution 3:

It follows my version of JaKXz answer that is supposedly more efficient by switching on inferred type. In the case of number and boolean the conversion is loose: in case of invalid input it will output NaN and false, respectively. You can work on this by adding your stricter validation and more types.

functionconvertToTypeOf(typevar, input)
{
  let type = typeof typevar;
  switch(type)
  {
    case"string":
      returnString.bind(null, input)();
    case"number":
      returnNumber.bind(null, input)();
    case"boolean":
      return input == "true" ? true : false;
    default:
      throw"Unsupported type";
  }
}

console.log(convertToTypeOf("string", 1));      // Returns "1"console.log(convertToTypeOf("string", true));   // Returns "true"console.log(convertToTypeOf("string", false));  // Returns "false"console.log(convertToTypeOf(1.2, "1"));         // Returns 1console.log(convertToTypeOf(1.2, "1.5"));       // Returns 1.5console.log(convertToTypeOf(true, "false"));    // Returns falseconsole.log(convertToTypeOf(false, "true"));    // Returns trueconsole.log(convertToTypeOf(1, "asd"));         // Returns NaNconsole.log(convertToTypeOf(true, "asd"));      // Returns false

Post a Comment for "How Can I Cast A Variable To The Type Of Another In Javascript"