Explicit casting
As with any strongly typed language, there comes a time where you need to explicitly specify the type of an object. This concept will be expanded upon more thoroughly in the next chapter, but it is worthwhile making a quick note of explicit casting here. An object can be cast to the type of another by using the < > syntax.
Let's rewrite our previous sample, and use explicit casting, as follows:
var item1 = <any>{ id: 1, name: "item 1" }; item1 = { id: 2 };
Here, we have now replaced the : any type specifier on the left-hand side of the assignment with an explicit cast of <any> on the right-hand side. This tells the compiler to explicitly treat the { id: 1, name: "item 1" } object on the right-hand side of the assignment operator as a type of any. In essence, this syntax is equivalent to our earlier examples and specifies the type of the item1 variable to be of type any (due to TypeScript's inferred typing rules). This then allows us to assign an object with only the { id: 2 } property to the variable item1 on the second line of code. This technique of using the < > syntax on the right-hand side of an assignment is called explicit casting.
While the any type is a necessary feature of the TypeScript language and is used for backward compatibility with JavaScript, its usage should really be limited as much as possible. As we have seen with untyped JavaScript, over-use of the any type will quickly lead to coding errors that will be difficult to find. Rather than using the any type, try to figure out the correct type of the object you are using, and then use this type instead.
We use an acronym within our programming teams—Simply Find an Interface for the Any Type (S.F.I.A.T), pronounced as sweat. While this may sound silly, it brings home the point that the any type should always be replaced with an interface, so simply find it. An interface is a way of defining custom types in TypeScript, which we will cover in the next chapter. Just remember that by actively trying to define what an object's type should be, we are building strongly typed code, and therefore, protecting ourselves from future coding errors and bugs.
In short, avoid the any type at any cost.