Chrissi Grilus
Chrissi Grilus

Reputation: 1395

Multiple types for a single variable (parameter/return type)

I am very new to Dart so excuse me if I didnt see this part.

I want to make a union type e.g. for a function input. In TS this would be:

let variableInput: string | number

typedef doesnt really define types but functions and enums dont really help too.

On the other side how should it look like when a function return either one or the other of two types? There must be something I dont see here.

Upvotes: 16

Views: 9973

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 127034

There are no union types in Dart.

The way to do this in Dart is returning/accepting dynamic as a type:

dynamic stringOrNumber() { ... }

void main() {
  final value = stringOrNumber();

  if (value is String) {
    // Handle a string value.
  } else if (value is num) {
    // Handle a number.
  } else {
    throw ArgumentError.value(value);
  }
}

See also: https://dart.dev/guides/language/sound-dart

Upvotes: 14

Related Questions