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
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.
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.