clutz
clutz copied to clipboard
fields without type information should still be promoted to TS class fields
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; }
}
This is partially fixed; however, the type of the outputted property value is currently always set to any.
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
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.
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;
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