◄►
Home

Type Casting

We all need to understand and deal with types. The problem is that even if we do, but we prefer programming without declaring types - like JavaScript programmers - the typed-language nazis descend apon us.

Javascript is loosely-typed. That means when you declare a new variable, say x = 1, you don't have to specify that 1 is a number.
When programs get complex, it becomes difficult to remember to make sure that each variable is of a type understood by all the functions accessing it.
The solution, according to Typed Nazis, is to complicate the language, and force everyone to double the size and complexity of their programs.
But there is another option: casting.
In this sense, casting means to ensure that a variable is of the type you need.
With a global cast method, you can forget all that checking.
So,
cast(1, 'Array') = [ 1 ]
cast(1, 'String') = "1"
cast(1, 'Boolean') = true
cast([1,2,3], 'String', ' - ') = "1 - 2 - 3"

...and so on.
It's forgiving, and it invokes no errors. Sure, there will be weird output at times, but it won't bring everything down when something happens to be the wrong type.
Less than half of your code really needs 100% type-safety coverage, and that small percentage can be dealt with by use of a cast function.
If you really want to complain when something is the wrong type, then just don't use cast - invoke an error instead!