-->

What is the current state of JavaScript static typ

2020-07-01 02:53发布

问题:

I know that the Google Closure Compiler does type checking—but are there any alternatives, preferably that aren't so tightly coupled with a library and optimizer?

If not, is there any way to have the Google Closure Compiler only do static analysis?

(By static analysis here, I mean things like defining types for arguments and so on that I can run through something to give me warnings if I make a typo or pass the wrong type.)

回答1:

There's Doctor JS, which is a Mozilla project that primarily (as I understand it, at least) does type-checking for JS.



回答2:

Microsoft's AJAX Minifier is a little more relaxed about the amount of prep you need to do to a JS file to get useful results out of it. You can run it with defaults and get out a highly minified file that still works with outside code: http://ajaxmin.codeplex.com/

But, both Closure Compiler and Ajax Minifier can only do very limited static analysis beyond basic linting, because of how Javascript is designed. Accessing an undeclared property may just be checking for undefined, assigning an undeclared variable just means declaring it in the global scope, assigning an object to a variable that contained a number is legal, etc. There's a lot that's legal in JS that your typical language (Java, C#) considers out of bounds, so without declaring types, boundaries and expectations for a specific compiler you're unfortunately limited in the errors you can prevent.

I'd be a bit more interested in something that can transform between the big 2 (MS and Google). It would be useful for IDE support, testing code size with advanced optimizations, etc.



回答3:

I have been quite happy with the intellij idea / webstorms editor, which parses jsdoc and does its own static analysis to flag potential or actual type safety errors. It has proven quite useful, although a bit of work was needed to get inheritance to work with some common frameworks. Due to the tons of approaches possible with javascript prototypal inheritance, the compiler needs a bit more help than for other languages.

It's a commercial tool, but I'm able to use it for java, php, javascript, python and ruby projects, all with some pretty decent static analysis and refactoring helpers. I used to do a lot with emacs and running node.js processes for jshint and closure compiler, but this is a lot less brittle.