ActionScript 3 Types Checking types


You can use the is operator to validate whether a value is of a certain type:

var sprite:Sprite = new Sprite();

trace(sprite is Sprite); // true
trace(sprite is DisplayObject); // true, Sprite inherits DisplayObject
trace(sprite is IBitmapDrawable); // true, DisplayObject implements IBitmapDrawable
trace(sprite is Number); // false
trace(sprite is Bitmap); // false, Bitmap inherits DisplayObject
                         // but is not inherited by Sprite.

There is also an instanceof operator (deprecated) which works almost identical to is except that it returns false when checking for implemented interfaces and int/uint types.

The as operator can also by used just like is operator. This is especially usefull if you use some smart IDE like FlashDevelop which will give you a list of all possible properties of explicit object type. Example:

for (var i:int = 0; i < a.length; i++){
    var d:DisplayObject = a[i] as DisplayObject;
    if (!d) continue;
    d.//get hints here

To get the same effect with is you would write (sligthly less convenient):

for (var i:int = 0; i < a.length; i++){
    if (a[i] is DisplayObject != true) continue;
    var d:DisplayObject = a[i] as DisplayObject;

Just keep in mind that when checking coditions with as operator, given value will be fist converted to specified type and then result of that operation will be checked if not false, so be careful when using it with possible false/NaN values:

if(false as Boolean) trace("This will not be executed");
if(false as Boolean != null) trace("But this will be");

Below table shows some basic values and types with result of type operators. Green cells will evaluate to true, red to false and greay will cause compile/runtime errors.

enter image description here