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.
Table of Contents
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.
1 2 3 4 5 6 7 | function fn(n) { ////infered type of n is any //dosomething return true; } |
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
.
1 2 3 4 5 6 7 | { "compilerOptions": { "noImplicitAny":true /* Enable error reporting when `this` is given the type `any`. */ } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 | function f(cond: boolean) { let x; // any if (cond) { x = "hello"; // infered as string } else { x = 123; // infered number } return x; // string | number } |
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.