dart-archive / js_facade_gen

Generates package:js Javascript interop facades for arbitrary TypeScript libraries
Apache License 2.0
161 stars 29 forks source link

Check parameters with union types at runtime #76

Open derekxu16 opened 4 years ago

derekxu16 commented 4 years ago
// 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);
}