Is it possible in Dart to have a list of exactly two types like you can in TypeScript? For example, something like this would compile:
List<int|String> foo = [
1,2,3,4,'baz'
];
while this wouldn't:
List<int|String> foo = [
1,2,false,4,'baz',[],3.0
];
No.
The Dart type system does not contain general union types. It cannot express "must be int
or String
" in the type system
The two available exceptions are:
Null
(nullable types, like int?
).Future
of the same thing (FutureOr
).Those two union types are known by the type system
For all other combinations, all you can do is to pick a type which is a super-type of both the types. In this situation, the nearest common supertype is Object
. The type system won't prevent you from putting booleans or lists into that.