18F / frontend

18F's Front End Guild –  content has been moved to https://github.com/18F/development-guide
Other
120 stars 29 forks source link

Add information about static type checking #171

Open toolness opened 7 years ago

toolness commented 7 years ago

I think it'd be really useful to have a section on static type chacking in the Front End Guide (#158). (Or alternatively, in some kind of general JS guide that can be used for both front and back-end JS development.)

The two big static type checkers for JS code right now are TypeScript (Microsoft) and Flow (Facebook).

Using either one of these is a great idea. Both of them are designed to allow you to incrementally introduce static typing into existing codebases, and continue programming using standard JS idioms. Their heavy use of type inference means that you don't actually have to add lots of annotation to benefit from them (i.e., using them doesn't mean your code suddenly has to look like Java).

I've found that using a static type checker:

Note that a static type checker is not a substitution for unit testing. IMO, the two are complementary and not at odds with one another.

Below are my thoughts on the two major choices.

TypeScript

Flow

toolness commented 7 years ago

Oh, I also just found out that TypeScript recently added support for type checking normal JavaScript files, i.e. non-type-annotated files. What's especially cool about this feature is that it parses JSDoc comments, so if you just document your code normally, TypeScript will essentially make sure that your documentation is accurate. And contributors to your codebase won't face a learning curve of learning a superset of JS.

toolness commented 6 years ago

For reference, we've just added some TypeScript support+code to https://github.com/18F/omb-eregs/pull/804. The main reason we chose TypeScript over Flow is because we're definitely going to be using a front-end library called ProseMirror, and it currently has annotations available in TypeScript but not Flow (and in general, TS seems to have a larger ecosystem of third-party annotations than Flow, potentially owing to its age).

So far so good!

toolness commented 6 years ago

In CALC, we've taken a different approach with https://github.com/18F/calc/pull/1670, using TypeScript's JS checking to check our legacy JS. We're currently white-listing which files to check by adding a // @ts-check at the top of any files we want checked.

One really nice thing is that it basically encourages us to document our code, because the JSDoc parameters are parsed as type annotations.