⭐ The Implicit 'Any' Type Error ⭐
We have this addTwoNumbers function:
export const addTwoNumbers = (a, b) => {
return a + b
}
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.
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
}
✍️ 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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)