Cast with runtime check

Topics: General
Sep 24, 2013 at 5:08 PM
Is it possible to perform runtime-checked cast or create helper method that does it for me?

The closest I got:
function cast<T>(x, t: Function): T {
    console.assert(x instanceof t, "Invalid cast");
    return x;
But that requires supplying type twice:
var foo = cast<String>(bar, String);
while I would prefer one of these:
var foo = cast<String>(bar);
var foo = cast(bar, String);
Sep 25, 2013 at 1:25 PM
Finally I got something that works:
function cast<T>(x, t: new() => T): T {
    console.assert(x instanceof t);
    return x;

var x = cast(foo, Whatever);
Sep 29, 2013 at 10:41 AM
@mwisnicki, furthermore instanceof won't work for primitives. You will need to check for primitives and use typeof instead.
Sep 29, 2013 at 12:14 PM
Actually, you can't call it with primitives:
var x = cast(foo, number); // Could not find symbol 'number'.
But that's OK since I need it just for classes.
Sep 29, 2013 at 12:42 PM
But here is slightly improved hack: