Closure-compiler: Generic types for es6 classes and getters

Created on 24 Nov 2016  路  5Comments  路  Source: google/closure-compiler

I am trying to annotate a getter on an es6 class with a generic type, but I can't seem to get it working.
A simplified example of the problem is:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @language_out ES5
// ==/ClosureCompiler==

/** @template T */
class X {

  /** @param {T} x */
  constructor(x) {
    this.x = x;
  }

  /** @return {T} */
  get foo() {
    return this.x;
  }
}

Produces:

JSC_TYPE_PARSE_ERROR: Bad type annotation. Unknown type T at line 9 character 15
  /** @return {T} */

which is the annotation on the foo getter (the constructor seems to work fine)

(Checked with https://closure-compiler.appspot.com)

ES6 Types

Most helpful comment

This is fixed now

All 5 comments

I am happy to look into it if anyone has a couple of pointers where a good place to start would be.

I think I promised someone I would fix this a while back, and then it turned out to be harder than I thought. I believe the @template annotation on the class gets copied as you'd expect, but the problem is that the getter lives outside of the class in the transpiled output:

/** @constructor @template T */
function X() {}

Object.defineProperties(X.prototype, {
  foo: {
    /** @return {T} */    // <- The compiler doesn't know what you mean by "T" here.
    get: function() { return this.x; }
  }
});

I suspect this will ultimately be fixed by having the typechecker understand ES6 classes (including getters and setters) directly instead of typechecking the output of the 6-to-5 conversion :(

I just stumbled upon this while converting my library to ES2015. What's the status of this? Is the typechecker still checking ES5 output only?

@b-strauss
The short answer is "yes, the type checker still only sees ES5 code".
Efforts are underway to change this.
Many optimization passes have now been updated to understand ES6 code, and it is now possible to request ES6 output from the compiler.
However, the type checker is one of the hardest parts to change and we're part way through switching from OTI (old type inference) to NTI (new type inference), which complicates things.

This is fixed now

Was this page helpful?
0 / 5 - 0 ratings