clutz icon indicating copy to clipboard operation
clutz copied to clipboard

fields without type information should still be promoted to TS class fields

Open gmoothart opened this issue 9 years ago • 5 comments

Fields defined in a constructor that don't have an explicit type annotation are skipped by gents. There are two issues here:

  • If we cannot infer a type we should just type to any, but we should add the class field anyway
  • If the type is easily inferred (like the example below) we should do so.

Example:

/**
 * @constructor
 */
var A = function() {
  /** @const */
  this.w = 5;
};

should be converted to:

class A {
  w: number = 5;
}

but currently is:

class A {
  constructor() { this.w = 5; }
}

gmoothart avatar Sep 21 '16 15:09 gmoothart

This is partially fixed; however, the type of the outputted property value is currently always set to any.

dpurp avatar Oct 12 '16 18:10 dpurp

We'd have to run type inference for that, and prefer using types determined by inference over the syntactical types. That might end up being tricky - it'd require figuring out that the current syntactical symbol correlates to some field of a type. That's messy, in particular for goog.module. Might

not be worth it?

Martin

mprobst avatar Oct 13 '16 19:10 mprobst

But this is a very restricted case, we only promote field initializers if the assignment is to a literal: https://github.com/angular/clutz/blob/52f0713977411a64e4fdedb71bd4e5e82d5c3bdb/src/main/java/com/google/javascript/gents/TypeConversionPass.java#L423

It seems like it shouldn't be that hard to construct the right JSTypeExpression if we know that the rhs is a NUMBER, STRING, etc.

gmoothart avatar Oct 13 '16 20:10 gmoothart

One option is to just omit the type annotation entirely and fall back on TypeScript inference. i.e. private n = 5; instead of today's private n: any = 5;

gmoothart avatar Oct 17 '16 20:10 gmoothart

Note that the type annotations appear to be added on the ClosureCompiler side of the fence.

https://github.com/google/closure-compiler/blob/005278687e8d51db7aee409c7631e93a20d3578b/src/com/google/javascript/jscomp/CodeGenerator.java#L262

dpurp avatar Oct 17 '16 22:10 dpurp