Skip to content
This repository has been archived by the owner on Dec 5, 2022. It is now read-only.

Check parameters with union types at runtime #76

Open
derekxu16 opened this issue Dec 17, 2019 · 0 comments
Open

Check parameters with union types at runtime #76

derekxu16 opened this issue Dec 17, 2019 · 0 comments

Comments

@derekxu16
Copy link
Contributor

derekxu16 commented Dec 17, 2019

// 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);
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

1 participant