DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #1

Image description

The Implicit 'Any' Type Error

We have this addTwoNumbers function:

export const addTwoNumbers = (a, b) => {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

This function takes in a and b and adds them together.

It looks like perfectly valid JavaScript. But TypeScript is not happy.

We get the following errors along with the line of code where they happen:

Parameter 'a' implicitly has an 'any' type.
Parameter 'b' implicitly has an 'any' type.
Enter fullscreen mode Exit fullscreen mode

This error occurs because TypeScript does not have enough information to infer a type, so it defaults to any.

👉 Solution:

The solution is to add type annotations to the function's arguments.

In this case, both a and b should be typed as number:

export const addTwoNumbers = (a: number, b: number) => {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

✍️ Summary:

TypeScript relies on type annotations to understand the contracts the function must meet. Type annotations are critical to understanding TypeScript.

Whenever you create a function, we must always specify the types of each argument!

I recommend turning on strict mode for all TypeScript projects.

When strict mode is enabled, we will get the implicitly has 'any' type error whenever you leave type annotations out.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)