Unsafe: a new library for transpiled ActionScript
Hi, ActionScript community!

The other day, I was thinking about the differences between the ActionScript VM in Adobe Flash runtimes and JavaScript VMs in web browsers. The AVM is very strict. If you try to assign something to a variable with a type that doesn't match, you'll get a run-time error. However, JavaScript is untyped, so anything can be assigned to any variable. It's like every variable is typed with *. When we transpile ActionScript or another language to JavaScript, all of our type checking happens at compile-time. We can take advantage of this difference to do some interesting things.

I'd like to introduce a new library for transpiled ActionScript called Unsafe. Using the new Unsafe.cast() function, you can bypass the usual type coercion that happens when you cast an object.

Let's say that you received some kind regular Object with x and y variables. Perhaps you parsed some JSON or received this object from a JavaScript library:

var point:Object = { x: 2, y: 10 };

Normally, if you wanted to assign this object to a variable with a type, you'd need to instantiate a new instance of a class and copy over the variables. With Unsafe.cast(), you can bypass that requirement.

var result:IPoint = Unsafe.cast( point );

That's it. The result variable is storing the same object, but to the compiler and your IDE, it looks like the object is now typed as an IPoint interface. Feel free to pass it to a function or assign it to another variable:

function addToPoint(point:IPoint, x:Number, y:Number):void
{
    point.x += x;
    point.y += y;
}
addToPoint( result, 1, 2 );

Be careful, though. There's a reason why this library is called "Unsafe".

Warnings

The important thing to understand is that the original object is completely unchanged. It's inheritance hierarchy has not been magically modified to include the IPoint interface. If you use the is operator, or if you do a real cast, it will fail:

if( result is IPoint )
{
    // result is not an IPoint, so this will be skipped
}
var newResult:IPoint = result as IPoint; // newResult will be null

The effects of an error like this may not be immediately apparent. Use this library with extra caution because it may be difficult to track down bugs as values propagate to other parts of your code. Unsafe is an interesting new addition to our toolbox, but you should actually try to avoid using it whenever possible.

Find Unsafe on Github

https://github.com/BowlerHatLLC/NextGenAS_Unsafe

Happy coding!

Josh Tynjala
NextGen ActionScript