Skip to content
This repository has been archived by the owner on Feb 22, 2018. It is now read-only.

[RFC] Add support for user-defined type guard functions #291

Open
vicb opened this issue Sep 29, 2015 · 2 comments
Open

[RFC] Add support for user-defined type guard functions #291

vicb opened this issue Sep 29, 2015 · 2 comments

Comments

@vicb
Copy link
Contributor

vicb commented Sep 29, 2015

TS 1.6 introduces user-defined type guard functions:

function isCat(a: Animal): a is Cat {
  return a.name === 'kitty';
}

It could help with type inference (ie removing explicit cast) in Angular.

Do we want to support this in ts2dart ?

It should transpile to

bool isCat(Animal a) {
  // ...
}

/ref microsoft/TypeScript#1007

@mprobst
Copy link
Contributor

mprobst commented Sep 30, 2015

I think that depends on whether dart2js is going to support that - otherwise we might end up producing invalid Dart code, or suboptimal Dart code.

@sigmundch, @alan-knight (sorry, picking two people at random). Code from ts2dart would look roughly like this:

class Banana { bananaMethod() {} }

bool isABanana(x) { return x is Banana; }

main(Object x) {
  if (isABanana(x)) {
        x.bananaMethod();    
  }
}

I think re-implementing the inference that x is a Banana in that if block, then renaming the variable and introducing a new free symbol, might be too clever for ts2dart.

@sigmundch
Copy link

as long as the function is small and has a single return like above, it is likely that dart2js will be able to inline it and correctly propagate that x is banana in the true branch. The easiest way to know for sure is to test it out explicitly and look at the dart2js output.

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

3 participants