Hacker News new | ask | show | jobs
by oinksoft 5004 days ago
Types are not classes! Why do people feel the need to constantly drag out this scarecrow? Having tools to perform static analysis is nothing but a good thing, and you need type data to do a great deal of this. Perhaps your project requirements are such that you never require type checking for your JS, but I can say that it's saved my ass a number of times when working on very large code-bases, and definitely has sped up my development cycle when working on hairy code.

This is a type, not a class, taken from a Closure Compiler docs annotation example:

  /**
   * Enum for tri-state values.
   * @enum {number}
   */
  project.TriState = {
    TRUE: 1,
    FALSE: -1,
    MAYBE: 0
  };
Now I can require this type in my code with standard JSDoc, which is what the compiler uses anyway for type-checking. It makes my code self-documenting (the Closure Linter, should you use it, will complain if you omit descriptions and the like too, if you find yourself getting lazy):

  /**
   * Do something...
   * 
   * @param state {project.TriState} The state ...
   */
  function doSomething(state) {
If you are documenting your code, you already do this. And now you have static analysis out-of-the-box ... not bad!
1 comments

The JSDoc system gets in the way too much, how for instance do you type variables which is something like:

  /** @type {myType} */ var thing = new myType( );
It gets way to verbose when compared to typescript which is something like:

  var thing : myType = new myType( );
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.
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.