When Dart types aren't optional

Dart, the structured web programming language, has a feature typically called "optional types". Dart claims that "type annotations don't affect the runtime semantics of the code". This post helps to explain when a type is and isn't optional, and what "type annotation" means as different than "type".

The Dart discussion mailing list kicked off a good thread about generics, which evolved into when types can be optional. The Dart community chimed in with great answers (thanks to Ladislav, Sam, John, Dirk, Ross, Bob, and Eli!). Bob Nystrom summed it up well, with some examples that I wanted to specifically highlight:

Bob writes:


Types aren't always annotations. There are type annotations, but there are also places where types appear in code that are not annotations. For example:

// type annotations: 

int i;
foo(int i) => ...
class Foo {
  int bar;
  int baz() => ...

// types that are not annotations:

foo is String;
new Foo();
new Foo<Bar>();
class Foo extends Bar implements Baz
{ ... } catch (SomeException ex) { ... } 

In every place where a type appears outside of an annotation, the type absolutely does have an important effect at runtime, and cannot be ignored. It's only type annotations that are "optional" in that sense.


Remember that Dart programs can run in two different modes: production mode and checked mode. In production mode, which is the default runtime mode, the program ignores type annotations. Production mode loads, compiles, and runs the code as fast as possible.

In the above examples, the types that are not annotations are respected in production mode.

In contrast, checked mode is an optional mode that does respect the type annotations and turns on "dynamic type assertions". In this mode, Dart will automatically insert assertions which check the types of objects with the declared static type annotations. If there isn't a match, an exception is raised to indicate the potential problem at the location of the mismatch. In general, we think developers should develop and test in "checked mode". Learn more about how to enable checked mode in the SDK and enable checked mode in Dartium.

In the above examples, checked mode will respect both the type annotations and the types that are not annotations.

As always, the Dart discussion mailing list is a great way to join the conversation and get your questions answered. You might also be interested in the Dart questions on Stack Overflow.

Popular posts from this blog

Lists and arrays in Dart

Converting Array to List in Scala

Null-aware operators in Dart