dart-archive / ts2dart

ts2dart TypeScript to Dart transpiler
Apache License 2.0
181 stars 62 forks source link

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

Open vicb opened 9 years ago

vicb commented 9 years ago

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 https://github.com/Microsoft/TypeScript/issues/1007

mprobst commented 9 years ago

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 commented 9 years ago

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.