noImplicitAny in TypeScript

noImplicitAny compiler option when set to true prevents TypeScript from implicitly assuming the type as any when the type is not specified or type cannot be inferred from its usage.

noImplicitAny Example

Whenever we do not annotate a variable with a type, TypeScripts tries to infer the type from its usage. When it cannot infer the type from its usage it infers the type as any.

For example, Typescript infers the type of function argument n as any.

You can stop this behavior by enabling the compiler flag noImplicitAny. To enable open the tsconfig file and add the "noImplicitAny":true under the compilerOptions.

Now the above function will throw the compiler error. Parameter 'n' implicitly has an 'any' type.

noImplicitAny error not reported for variable declaration

Look at the following example. We have declared the variable x without assigning it to any type. Hence typescript infers its type as any. But this does not throw any compiler error even if we set "noImplicitAny":true in compiler option

This is because the typescript does a control flow analysis and infers the type correctly at every usage of x. Therefore, the compiler does not throw any errors.

Reference

  1. Reference
  2. noImplicitAny error not reported for variable declaration
  3. Control flow analysis for implicit any variables

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top