Type test operators

The as, is, and is! operators are handy for checking types atruntime.

OperatorMeaning
asTypecast (also used to specify library prefixes)
isTrue if the object has the specified type
is!False if the object has the specified type

The result of obj is T is true if obj implements the interfacespecified by T. For example, obj is Object is always true.

Use the as operator to cast an object to a particular type. Ingeneral, you should use it as a shorthand for an is test on an objectfollowed by an expression using that object. For example, consider thefollowing code:

  1. if (emp is Person) {
  2. // Type check
  3. emp.firstName = 'Bob';
  4. }

You can make the code shorter using the as operator:

  1. (emp as Person).firstName = 'Bob';

Note: The code isn’t equivalent. If emp is null or not a Person, the first example (with is) does nothing; the second (with as) throws an exception.