0

Is there a generic way to explicitly cast a variable to a specific type? For example:

var b = true;
var str = "";
var n = 5;
cast(someVariable, typeof b);   //someVariable become a boolean
cast(someVariable, typeof str); //someVariable become a string
cast(someVariable, typeof n);   //someVariable become an integer

where a cast is supposed to be that magic casting method.

That's obvious that I can just enumerate in a switch all possible types. But is there a [beautiful] native way to do that?

2
  • 1
    Can't you use something like Boolean( someVariable ), Number( someVariable ); ? Commented Jul 20, 2016 at 10:31
  • 1
    @MohitBhardwaj I can, but the thing is I don't always know the type of second argument. Commented Jul 20, 2016 at 10:37

1 Answer 1

4

You can do it using mapping:

var castMap  = {
    "boolean" : Boolean
};
var b = true;
var someVariable = "true";
castMap[typeof(b)](someVariable)
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, that looks more simple than switch operator. Thank you
This isn't a good answer. Number(val) doesn't cast types like in c.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.