Ofek Gila Ofek Gila - 1 year ago 69
Javascript Question

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 work

so that convertToType(1, "15") returns 15, convertToType("1", 15) returns "15", convertToType(false, "True") returns true, etc.

Is this possible?

Answer Source

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:

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

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

I would also suggest looking into TypeScript for your project.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download