How To Solve The Error “Parameter ‘#’ Implicitly Has An ‘Any’ Type” In TypeScript?

Parameter ‘#’ implicitly has an ‘any’ type in TypeScript

Knowing how to solve the error “Parameter ‘#’ implicitly has an ‘any’ type” in TypeScript will be very helpful when working with a function. So how to do it? Let’s go into detail.

The reason for the error “Parameter ‘#’ implicitly has an ‘any’ type” in TypeScript

Let’s see the example below to know how the error happens:

Example:

const animalName = (list, index): string => {
  	return list[index];
};

const animals = ["Dog", "Cat", "Mouse", "Turtle", "Snake", "Fox", "Chicken", "Pig", "Eagle"];
console.log(animalName(animals, 1));

Error:

Parameter 'list' implicitly has an 'any' type.
Parameter 'index' implicitly has an 'any' type.

This error happened because I created a parameter in the animalName function without a set type. And it is not allowed in Typescript.

Solutions for this error

Set type

The most obvious solution for this error is to set the correct type for your parameters.

Example:

const animalName = (list: string[], index: number): string => {
	return list[index];
};

const animals = ["Dog", "Cat", "Mouse", "Turtle", "Snake", "Fox", "Chicken", "Pig", "Eagle"];
console.log(animalName(animals, 1));

Output:

"Cat"

Here I explicitly set the list and index parameters to string array type and number type so the error goes away.

Use ‘any’ type

If you are unsure what will be passed in parameters, you can set explicit type to any and make a type guard like check type.

Example:

const animalName = (list: any, index: any): string => {
    if (typeof list == "object" && typeof index == "number") {
        return list[index];
    } else {
        return "Invalid input";
    }
};

const animals = ["Dog", "Cat", "Mouse", "Turtle", "Snake", "Fox", "Chicken", "Pig", "Eagle"];
console.log(animalName(animals, 1));
console.log(animalName(undefined, 0));

Output:

"Cat" 
"Invalid input"

Here I set list and index parameters to any type, and in the function, I make an if...else statement to check if the argument is valid to execute code. An array is just a special object, so an array will be an object. But I do not recommend this solution because if you abuse this situation, it will make your variable become a dynamic type, just like in Javascript, and the power of Typescript will be lost.

Ignore the error

If you don’t care about the error and want to turn it off, you can set the optional "noImplicitAny" to false in tsconfig.json file.

{
    "noImplicitAny": false
}

Summary

In this article, I’ve shown you how to solve the error “Parameter ‘#’ implicitly has an ‘any’ type” in TypeScript. You can set explicit type to the correct type that value will be passed or set to any type. Or you can ignore it by setting the optional "noImplicitAny" to false. Let’s try them. Good luck for you!

Maybe you are interested:

Leave a Reply

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