The reasons to avoid using any type

The any is a wildcard type that allows not only any type but also to change the type at will. There are many problems with any. The first one is that it is hard to follow what type is a variable; we are back to how JavaScript is written:

let changeMe: any;
changeMe = 1;
changeMe = "string too";
changeMe = false;

The use of any should be avoided because it can hold a value that is not as expected and still it can compile because TypeScript does not know the type and cannot perform validation:

let anyDangerous: any = false; // still not a boolean, neither a string
console.log(changeMe.subString(0, 1)); // Compile, but crash at runtime

The only reason to use any is in two situations. The first one is that you are migrating code from JavaScript to TypeScript. Migrating code can take a long time and TypeScript is built naturally in a way that you can be in a hybrid mode for a while. It means that not only you can turn down some strictness of the compiler options, but also that you can create functions, variables, and types that are not fully detailed in terms of type by allowing any.

The second situation where any is potentially acceptable is when you are in a situation that you cannot figure out the type in some advanced scenario and you must move on. The latter should be a signpost and must have a follow-up because we do not want to make it a habit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.161.132