js_facade_gen icon indicating copy to clipboard operation
js_facade_gen copied to clipboard

Check parameters with union types at runtime

Open derekxu16 opened this issue 5 years ago • 0 comments

// For a TypeScript function like:
declare class X {
  /**
   * Prints "it's a number" if `x` is a number or "it's a string" if `x` is a string.
   *
   * Throws an error otherwise.
   */
  f(x: number|string): void;
}

// We can generate extension methods to check the type of parameter x at runtime
@JS()
library X;

import "package:js/js.dart";

@JS()
class X {}

@JS("X")
abstract class _X {
  /// Prints "it's a number" if `x` is a number or "it's a string" if `x` is a string.
  /// Throws an error otherwise.
  external void f(Object /*num|String*/ x);
}

extension XExtensions on X {
  void f(Object /*num|String*/ x) {
    assert(x is num || x is String);
    final Object t = this;
    final _X tt = t;
    return tt.f(x);
  }
}

void main() {
  final X x = X();
  x.f(123);
  x.f('abc');
  x.f(true);
}

derekxu16 avatar Dec 17 '19 23:12 derekxu16