Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 61 ยท Types and Operators

The Type System: dynamic, Object and Type Inference

Tour Dart's sound type system: Object and Object?, dynamic, void, Never, type inference rules, the is and as operators, runtimeType and how types relate.

Dart is a statically typed language with a sound type system. "Statically typed" means the compiler knows the type of every expression before the program runs. "Sound" means the compiler's knowledge can be trusted: if it says a variable is a String, then at runtime that variable really holds a String (or a subtype of it). Together with null safety, this removes many errors long before your users see them.

Earlier lessons used types one at a time. This lesson shows how they fit together: which type sits at the top, what dynamic really does, what void and Never are for, how Dart infers types you do not write, and how to test and cast at runtime. Dart code here is read-only; the stand-ins use TypeScript's closest equivalents, and the lesson says where they differ.

Everything is an Object

In Dart every value is an object, including numbers, booleans, functions and null. Every non-null object is an instance of Object, the root of the class hierarchy. Object offers only a few members: toString(), ==, hashCode, runtimeType and noSuchMethod. So if a variable has the static type Object, those are the only things you can use on it without a check.

DART
void main() {
  Object thing = 42;
  print(thing.toString());      // 42
  print(thing.hashCode == 42.hashCode);   // true
  // print(thing + 1);          // error: '+' isn't defined for Object
  thing = 'now a string';       // allowed: a String is an Object
  print(thing);
}

Since null is not an Object, the top type of the whole system is Object? (an object or null). Null is the tiny type whose only value is null. The hierarchy looks like this:

flowchart TD
    T["Object? (top type)"] --> O["Object"]
    T --> N["Null"]
    O --> num["num"]
    O --> S["String"]
    O --> B["bool"]
    O --> L["List, Map, your classes ..."]
    num --> I["int"]
    num --> D["double"]
    I --> NV["Never (bottom type)"]
    D --> NV
    S --> NV
    N --> NV

Object? is above every type; Never is below every type. int and double are both subtypes of num.

dynamic: turning checks off

dynamic is a type that tells the compiler: "do not check what I do with this value." Any method call on a dynamic value compiles, and failures are found at runtime.

DART
void main() {
  dynamic value = 'hello';
  print(value.length);       // 5, resolved at runtime

  value = 12;
  print(value.length);       // compiles! but throws NoSuchMethodError at runtime
}

Compare with Object?. Both can hold anything, but Object? keeps the safety net: you may only use Object's members until you test the type. dynamic removes the net.

Declared type Can hold Calling .length Checked by compiler
Object? anything, including null error, until you test the type yes
Object anything but null error, until you test the type yes
dynamic anything compiles, may fail at runtime no

Use dynamic rarely: when you really work with data of unknown shape, such as decoded JSON, and even then convert it into typed objects quickly. A good habit is to prefer Object? for "anything" and cast when you know more. Be aware that var x; (no initializer, no type) declares a dynamic variable, which is a common accidental use.

TypeScript unknown versus any (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

void and Never

Two special types describe functions that do not hand back a normal value.

void means "the result of this function is not meant to be used". A function with return type void returns nothing useful, and you cannot use the call as a value.

Never means "this function never returns normally". It always throws or loops forever. Because it never returns, Never is the bottom type: it is a subtype of every type, so a call to a Never function can stand in wherever any type is expected.

DART
void logLine(String message) {
  print('[log] $message');
}

Never fail(String message) {
  throw StateError(message);
}

int parsePositive(String text) {
  var n = int.tryParse(text);
  if (n == null || n <= 0) {
    fail('Expected a positive integer, got "$text"');   // never returns
  }
  return n;     // n is promoted to int because fail() cannot return
}

The last comment shows a nice effect. After fail(...), the compiler knows the code beneath cannot be reached when n == null, so it promotes n to a plain int. This is the same type promotion you met in the null safety lesson.

TypeScript void and Never (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Type inference

You can leave types out and Dart works them out. The rules are simple and consistent.

DART
void main() {
  var a = 3;               // int
  var b = 3.5;             // double
  var c = 'text';          // String
  var d = [1, 2, 3];       // List<int>
  var e = [1, 2.5];        // List<num>
  var f = [1, 'two'];      // List<Object>
  var g = [1, null];       // List<int?>
  var h = {'a': 1};        // Map<String, int>
  var i = <int>[];         // List<int>, from the explicit type argument
}

For a list literal, Dart finds the closest common supertype of the elements. Mixed numbers become List<num>; a number and a string give List<Object>. Inference also flows from context. When you assign to a typed variable, List<double> xs = [1, 2]; works: because the expected type is known, the literals 1 and 2 are read as doubles (this works for integer literals only, not for int variables).

A variable declared with var or final and an initializer takes the type of that initializer, and that type is then fixed. Be careful with declared functions: if you leave out the return type, Dart does not infer it from the body, it treats the function as returning dynamic. Closures, by contrast, get their return type inferred. Write return types on declared functions so that your API reads clearly and stays checked.

Testing and casting at runtime

Because values can have more specific types than their variables declare, Dart lets you test and cast. You saw the operators is, is! and as in Booleans and Operators. The best use is with promotion:

DART
String describe(Object? value) {
  if (value == null) return 'nothing';
  if (value is int) return 'int ${value + 1}';       // promoted to int
  if (value is String) return 'text of ${value.length} letters';
  if (value is List) return 'list with ${value.length} items';
  return 'something else: ${value.runtimeType}';
}

void main() {
  print(describe(41));
  print(describe('Dart'));
  print(describe([1, 2, 3]));
  print(describe(3.5));
  print(describe(null));
}
TEXT
int 42
text of 4 letters
list with 3 items
something else: double
nothing

The runtimeType property returns a Type object describing the actual class of a value. It is mostly useful for printing and debugging. Avoid comparing runtimeType for logic, because it ignores subclassing: use is instead. A cast with as is a promise that can fail, and the failure is a TypeError. Use it only after you know the answer, such as after a successful is check elsewhere.

TypeScript Type tests and promotion (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Think of the type system as a conversation with the compiler. Write types where they document intent (function signatures, public fields), omit them where they are obvious (local variables), and let is checks tell the compiler what you learned about a value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type is the top of Dart's type hierarchy once null safety is considered?

    Object excludes null, so the type that includes every value, null included, is Object?. dynamic is a special type that disables checking rather than a normal top type.
  2. 2. What is the key difference between dynamic and Object??

    Both can hold any value, but dynamic skips static checking, so mistakes show up at runtime. Object? keeps compile-time safety.
  3. 3. What does a function declared with return type Never do?

    Never is the bottom type and is used for functions that always throw or never complete, which also helps the compiler with type promotion.
  4. 4. What type does Dart infer for var x = [1, 2.5];?

    The elements share the closest common supertype, num, because int and double are both subtypes of num.
  5. 5. Why should you prefer is over comparing runtimeType in logic?

    An is check is true for subclasses too and promotes the variable inside the branch, while runtimeType equality ignores the subclass relationship.

Summary

  • Every value is an object; Object is the root of non-null types and Object? is the top type of the system.
  • dynamic switches off compile-time checks; prefer Object? plus is tests when you must hold unknown values.
  • void marks results not meant to be used; Never marks functions that never return and is a subtype of everything.
  • Inference picks the closest common type, for example List<num> for mixed numbers; write types where they document intent.
  • Use is and is! to test and promote, as only when you are sure, and runtimeType for debugging.

Next, learn a compact way to bundle several values together in Records.