TypeScript works as your code bodyguard, saving you from bugs. But using “any” may look cool but completely untrustworthy and doesn’t protect your code from crashing.
Here, are the reasons why “any” is problem:
- No Type Safety: TypeScript saves you from must of the problem at runtime, which is it’s advantage. This is possible due to the feature of called Type Safety. But “any” turns that off.
Example:
function displayName(data:any){
console.log(data.firstName);
What if ‘data’ has no ‘name’ ?
→ Uh-oh! with out type check, we will only find out issues when it’s too late.
- Hard to Understand:
Using any makes your code hard to understand and add confusion when someone else try to read your code.
Example:
const displayName:any = fetchUserData();
console.log(displayName.firstName);
Clearly, types make your code more readable and debuggable.
- Disable main advantages:
TypeScript’s main advantages is it Type Safety. When you use “any” it disables it’s main advantage.
Example:
const message:any = "Hello,Welcom to my blog!!";
console.log("message");
When, we use “any” it leads us to more error and type error which result to crashing our application.
Let us understand with a good and bad example:
Bad Example:
const Button:any = ({label})=> <button>{label}</button>;
Better Example:
interface ButtonProps{
label:string;
}
const Button:React.Fc<ButtonProps>=({label})=> {
<button>{label}</button>
};
Now, “label” is sure to be a “string”, keep it safe. If “label” is not passed “string” it gives us an “type error error.”
Conclusion:
“any” may look like more flexible and shortcut for some of the cases but it disables advantages of using TypeScript. Use specific type for variable ,props etc to make your code more clean and understandable.
So, next time when you think of using “any”, ask yourself wheather you want to make your code messy ???. The answer would always be NO!!
Share you experience in the comment below. Have you ever used “any” to escape from “type error” ??
And on my next blog will be on the topic "How can we replace "any" with "Types" of TypeScript? Stay tune!
Top comments (0)