noImplicitAny - Best Practices

July 2017
September 2017

Should I use the noImplicitAny TypeScript compiler flag - yes or no?

What the noImplicitAny compiler option does, is it basically converts TypeScript from an optionally-typed language to a necessarily-typed language. This gets TypeScript a little further away from being a superset of JavaScript, since a simple

function logMe(x) {
  console.log(x);
}
// error TS7006: Parameter 'x' implicitly has an 'any' type.

would throw an error. You would have to explicitly declare that x is of type any:

function logMe(x: any) {
  console.log(x);
}
 // OK

This means that migrating existing JS codebases to TS becomes much more work than just changing the file extension. It also means, that when coding you need to have much more focus on the types, since the compiler will always complain if you don’t specify the type. Since explicitly declaring any when in reality it’s not any is considered bad practice, you’re confronted with assigning correct types much earlier on in the development process. Without an explicit any declaration it could just mean “I was just too lazy to annotate the types here correctly”.

Whether this is a good or a bad thing is strongly debatable. The community seems to be split on the issue. Here are some industry-leading TypeScript projects and whether they use the noImplicitAny compiler flag or not:

Project Uses noImplicitAny
Angular YES
RxJS YES
VSCode NO
Babylon.js NO

So I’m adding my two cents to the discussion to break the tie: We’re using TypeScript for a reason, since types provide meaningful extra information that serve as documentation and for catching errors early on. So why be inconsistent with it and only add types somewhere? Add them everywhere and be done with it. Otherwise you'll have to do additional thinking "hmm should I add types here, I'm kinda too lazy, but it would be good, but I've got other work to do... Let's do it tomorrow". Thus my recommendation is to set noImplicitAny to true.

Interested in TypeScript?