Borislav Hadzhiev
Tue Mar 08 2022·2 min read
Photo by Thought Catalog
The "Parameter 'X' implicitly has an 'any' type" error occurs when a
function's parameter has an implicit type of any
. To solve the error,
explicitly set the parameter's type to any
, use a more specific type, or set
noImplicitAny
to false
in tsconfig.json
.
Here is an example of how the error occurs.
// ⛔️ Error: Parameter 'a' implicitly // has an 'any' type.ts(7006) function sum(a, b) { return a + b; }
The parameters of the sum
function were not explicitly typed, so TypeScript
set them to have an implicit type of any
.
The first way to solve the error, is to explicitly set the type of the
parameters to any
.
function sum(a: any, b: any) { return a + b; } console.log(sum(10, 50)); // 👉️ 60
We explicitly typed the a
and b
parameters to have a type of any
. The type
is no longer implicitly set, so we don't get the error.
The same approach can be used with arrow functions, callbacks, etc.
const sum = (a: any, b: any) => { return a + b; }; console.log(sum(10, 50)); // 👉️ 60
A much better solution is to be more specific when setting the parameter's type.
function sum(a: number, b: number) { return a + b; } console.log(sum(10, 50)); // 👉️ 60
Now the parameters in the sum
function are explicitly typed to be numbers
.
This is much better, because the any
type effectively turns off type checking
in TypeScript.
If you don't like this behavior and want to turn off getting errors when values
are implicitly set to any
, set the noImplicitAny
option to false
in your
tsconfig.json
file.
{ "compilerOptions": { // ... other properties "noImplicitAny": false } }
The noImplicitAny
option defaults to true
, if you've set the strict
property to true
.
When TypeScript can't find type annotations for a value and they can't be
inferred, it falls back to a type of any
.
noImplicitAny
to true
, every time TypeScript can't find or infer type annotations for a value, it will issue an error.By turning it off, you suppress the error messages, but in general, the more strict you write your TypeScript code, the less likely it is you will get unexpected runtime errors.