Skip to main content
The as operator is a binary operator used to perform an explicit type cast. It asserts that an object is an instance of a specific type, instructing the compiler to treat the object as that target type while enforcing a runtime check to validate the assertion.

Syntax

expression as TargetType

Operational Semantics

The as operator functions as a runtime assertion. When executed, the Dart runtime evaluates the relationship between the runtime type of expression and the TargetType.
  1. Successful Cast: If the runtime type of expression is a subtype of TargetType (or exactly TargetType), the operator returns the object. The static type of the resulting expression becomes TargetType.
  2. Failed Cast: If the runtime type of expression is not a subtype of TargetType, the operator throws a TypeError. This is an unhandled exception that interrupts execution flow.

Interaction with Null Safety

The behavior of the as operator is strictly governed by Dart’s sound null safety system:
  • Casting to Non-Nullable: If expression evaluates to null and TargetType is non-nullable (e.g., String), a TypeError is thrown immediately because Null is not a subtype of the non-nullable type.
  • Casting to Nullable: If TargetType is nullable (e.g., String?), casting null is a valid operation and returns null.

Static Analysis

The Dart analyzer evaluates as expressions at compile-time to identify logical inconsistencies:
  • Unnecessary Casts: If the static type of expression is already a subtype of TargetType, the analyzer may flag the cast as redundant.
  • Impossible Casts: If the static types are disjoint (e.g., casting an expression statically known as int to String), the analyzer reports a compile-time error, preventing the code from compiling.

Examples

Successful Cast The following code successfully casts a variable typed as Object to String because the underlying runtime value is a string.
void main() {
  Object genericValue = 'Dart Syntax';
  
  // Runtime check passes; static type becomes String
  String specificValue = genericValue as String; 
  
  print(specificValue.length); // Accessing String-specific property
}
Runtime Failure The following code compiles because Object can theoretically hold an int, but fails at runtime because the actual value is a String.
void main() {
  Object genericValue = 'Dart Syntax';
  
  try {
    // Throws TypeError: type 'String' is not a subtype of type 'int'
    int number = genericValue as int; 
  } catch (e) {
    print(e.runtimeType); // TypeError
  }
}
Null Safety Violation Casting null to a non-nullable type triggers an exception because Null is not a subtype of String.
void main() {
  Object? nullableValue = null;
  
  // Throws TypeError: type 'Null' is not a subtype of type 'String' in type cast
  String nonNullable = nullableValue as String; 
}
Master Dart with Deep Grasping Methodology!Learn More