Type casting is where we override the compiler, and tell it the type of a variable or function.
In Typescript, this is done using the as
keyword.
A type cast disables all of the compiler's safety features. The moment we use a type cast, we're telling the compiler to completely trust us. In effect, we're telling the compiler that we know best.
Sometimes, we have no choice.
- Sometimes, the Typescript compiler can't work out for itself what type something is. The type inference algorithm isn't all-powerful, especially where generics are involved!
- Sometimes, a function is there specifically to do a type cast (for example, the smart constructors for branded and flavoured types).