Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

To reiterate, I want to be able to dynamically cast variables to the types of other variables.

Is this possible?

like image 854
Ofek Gila Avatar asked Dec 19 '22 15:12

Ofek Gila


1 Answers

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

like image 152
marsouf Avatar answered May 05 '23 08:05

marsouf