User Guide
Data types 57
In order to provide compile-time type checking, the compiler needs to know the data type
information for the variables or expressions in your code. To explicitly declare a data type for a
variable, add the colon operator (
:) followed by the data type as a suffix to the variable name.
To associate a data type with a parameter, you use the colon operator followed by the data
type. For example, the following code adds data type information to the
xParam parameter,
and declares a variable
myParam with an explicit data type:
function runtimeTest(xParam:String)
{
trace(xParam);
}
var myParam:String = “hello”;
runtimeTest(myParam);
In strict mode, the ActionScript compiler reports type mismatches as compiler errors. For
example, the following code declares a function parameter
xParam, of type Object, but later
attempts to assign values of type String and Number to that parameter. This produces a
compiler error in strict mode.
function dynamicTest(xParam:Object)
{
if (xParam is String)
{
var myStr:String = xParam; // compiler error in strict mode
trace("String: " + myStr);
}
else if (xParam is Number)
{
var myNum:Number = xParam; // compiler error in strict mode
trace("Number: " + myNum);
}
}
Even in strict mode, however, you can selectively opt of out compile-time type checking by
leaving the right side of an assignment statement untyped. You can mark a variable or
expression as untyped by either omitting a type annotation, or using the special asterisk (
*)
type annotation. For example, if the
xParam parameter in the previous example is modified so
that it no longer has a type annotation, the code will compile in strict mode:
function dynamicTest(xParam)
{
if (xParam is String)
{
var myStr:String = xParam;
trace("String: " + myStr);
}
else if (xParam is Number)
{
var myNum:Number = xParam;