Hacker News new | ask | show | jobs
by oinksoft 5001 days ago
Actually that's not quite accurate. The Closure Compiler doesn't need you to tell it that `thing` is a myType, it knows that, asuming myType is defined in your compiled code, or you provide an extern specifying what myType means. And I might be wrong about that last bit even; the compiler may always know that `new Foo` returns a {Foo} regardless of context ... I would have to check the compiler source to be certain.

Also, I think that the first example is more likely to be written as follows (in the case where type data cannot be inferred):

  /**
   * Description of the variable.
   *
   * @type {my.UnionType}
   */
  var foo = { ... };
Whatever "..." may be. It's common to document the meaning of variables where explicit typing like this is important, just like in well-documented Java and PHP code.
1 comments

The benefit of typing javascript is for the developer and not the compiler, therefore telling closure compiler that a variable is a type is to decrease the chance of mistakes. Closure compiler also is buggy and isn't as smart as we would like to think it is, sometimes you have to prod it into the right direction. It was a simplified example, something better would be:

  /** @type {myType} */ var thing = function_that_returns_a_myType( );
The point is using comments for typing a language is messy and takes up far more space than required.