Last updated: Feb 28, 2024
Reading timeยท3 min
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 are not explicitly typed, so TypeScript set
them to have an implicit type of any
.
any
One 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
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
Here is an example that sets the parameter of a callback function to have a type
of any
.
const arr = ['bobby', 'hadz', 'com']; arr.forEach((item: any) => { console.log(item); });
This isn't necessary in this particular case because TypeScript is sometimes able to infer the type of a variable.
However, if the arr
variable is implicitly typed as any, then its items will
also have an implicit type of any
which would cause the error.
You might also have to turn off type checking for event handler functions, e.g. in Angular.
function handleClick(event: any) { console.log(event); }
A much better solution is to be more specific when setting the type of the parameters.
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
.
any
type effectively turns off type-checking in TypeScript.If you need to declare a function with a variable number of arguments, click on the following article.
If you don't like this behavior and want to suppress errors when values are
implicitly typed as any
, set the noImplicitAny
option to false
in your
tsconfig.json file.
{ "compilerOptions": { // ... other properties "noImplicitAny": false } }
If the strict
property is set to true
, the noImplicitAny
option defaults
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
, TypeScript issues an error every time it can't find or infer type annotations for a value.By turning it off, you suppress the error messages. However, the more strictly you write your TypeScript code, the less likely you are to get unexpected runtime errors.
You can also use a comment to disable type checking.
You can learn more about the related topics by checking out the following tutorials: