DEV Community

Gabriele Buffolino
Gabriele Buffolino

Posted on • Originally published at bite-sized.hashnode.dev on

A TypeScript misunderstanding

Fortunately, I have not seen this many times. Still, it highlights a deep TypeScript misunderstanding and, even worse, a huge knowledge gap.

Have a look at this code snippet.

function myFunction(isIt: boolean) {
    if (isIt === true) {
        // do some stuff...
    } else {
        // do some other stuff...
    }
}

Enter fullscreen mode Exit fullscreen mode

Anything weird? Yes, you got it, that === operator. It won't cause any major disruption at runtime, but...do we really need it?

As the === operator checks also for operand types, a question arises: are we expecting the isIt parameter to be other than a boolean? If not, then we can just get rid of it. If yes, then why do you use TypeScript in the first place? TypeScript is all about finding potential type inconsistencies bugs at compile time rather than at runtime.

The isIt parameter is guaranteed at compile time to be a boolean. The only way it cannot be a boolean at runtime is that its value comes from an external source (API call, file system read, whatever is outside our code) and has not been validated properly.

So we have several problems with this pretending-to-be-innocent code:

  • If the value comes from an external source, we are missing validation at some point in our code. The severity of this issue depends on the application itself, but we have a potential bug here.

  • If the value does not come from an external source, or it is validated when it enters the application, then is pointless as type checking is performed by TypeScript. No need to do it ourselves.

This pretending-to-be-innocent code revealed the lack of basic TypeScript knowledge. That was scary enough for an innocent === operator.

Conclusions

Be sure to validate your data and, even more importantly, spend time understanding the technologies you're going to be using in your project.

To the next bite!

Top comments (0)