Why ‘optional’ is powerful in Typescript

Coming from another language, feeling like the optional type is pointless?

Like many others, perhaps you have also noticed that it is indeed possible to define a class or even an interface with a sub-interface. This prevents you from creating the object without defining all the properties, they’re not even nullable and that’s great!

Let’s say you have the following definition:

You may however also have realized that it is entirely possible to initialize this object with the thirdProp as null. Why is this?

This is where Typescript can be different, especially if you’re coming to it from other languages with Type Safety that has been baked in from the start, such as Java, Kotlin or Swift.

Setting a property as optional (by providing an ? right before the : in the definition) makes tells the Typescript compiler it is OK to create an object, or that this object can exist, without that property.

This is extremely powerful.

Typescript is not a language that can do anything at runtime. Instead it is a superset of Javascript, which is ultimately compiled down to Javascript. That means it cannot do anything that Javascript cannot do.

However, it allows us greater safety in asserting what type something is, whether that is a simply variable, an object property or even a full API response.

When we can consistently rely on that to be correct, we can expect the Javascript that the compiler results in, to be reliable code that will produce much fewer runtime errors, but at least only based on user inputs and not developer sloppiness.

That is a MASSIVE step forward in the Javascript ecosystem.

Leave a Reply