Its possible to use type from TypeScript in Dart?

Sample (TypeScript):

export type Speed = 'very slow' | 'slow' | 'normal' | 'fast' | 'very fast';

public getRealSpeed(speed: Speed): number {
    switch(speed) {
       ...
    }

    return 0;
} 

or

public getRealSpeed(speed: 'slow' | 'fast' | 'unknown'): number {
    switch(speed) {
       //TODO
    }

    return 0;
} 

1 Answers

1
lrn On

You can use a Dart enum for the same behavior:

enum Speed { verySlow, slow, normal, fast, veryFast; }
int getRealSpeed(Speed speed) {
  switch (speed) {
    case Speed.verySlow: return 1;
    ...
    case Speed.veryFast: return 99;
  }
  return 0;
}

This does mean that you have to convert strings values to Speed instances explicitly, perhaps using

const speedByName = {
  "very slow": Speed.verySlow,
  "slow": Speed.slow,
  "normal": Speed.normal,
  "fast": Speed.fast,
  "very fast": Speed.veryFast,
};