Strict Mode and Casting in Flash Actionscript 3
Today I came across a programming error when I tried to find the z-index of the movieclip (my_mc) when it is being clicked. Below was my code:
my_mc.addEventListener(MouseEvent.CLICK, doClick);
function doClick(e:MouseEvent):void
{
trace (getChildIndex(e.target)); // throw a compiled time error
}
When I tested the movie, Flash returned a complied time error- 1118:Implicit coercion of a value with static type Object to a possibly unrelated type flash.display:DisplayObject.
I was scratching my head and couldn’t quite figure out what when wrong. It took me a while to realise that Flash was giving me the error because the complier didn’t know that e.target in this case was indeed a movieclip. When I turned off the Strict Mode error warning at the Actionscript 3 Settings at the Publishing Settings page, Flash compiled the movie successfully and everything ran fine.
Naturally I was not satisfied having to ignore the error in order to run the movie. So I did a little more research and found that I could explicity type cast an object if the compiler didn’t know what the object type was. There were bascially two ways to solve the above problem. Instead of:
trace (getChildIndex(e.target));
Replace that with:
trace (getChildIndex(e.target as MovieClip));
Or with:
trace (getChildIndex(MovieClip(e.target)));
So now I have the proper code that meets the strict typing requirement and can be compiled successfully. ![]()

worth noting that you get 2 different results with the 2 different methods of casting, if the cast fails.
Using the ‘as’ keyword the result of the cast would be null and the movie would continue to run. Using a standard cast the player would throw an error.
Thanks Tink. Good point.