Optional vs Nullable In Typescript/Angular

An interesting question came up recently about the difference between the “optional” flag in Typescript, and setting something as null. More importantly, it was a question of whether the following were synonymous :

export class MyClass {
  myProperty? : string;
}
export class MyClass {
  myProperty : string | null;
}

The answer is no, these are not the same thing, but it took some explaining to do to people from backgrounds that do not have a “optional” flag, and instead just use a nullable type. For instance, in C#, we may do something like so :

class MyClass 
{
    public string? MyProperty { get; set;}
}

This tells the compiler/runtime that MyProperty is nullable, and by default, will have a null value if no value is given. However in Typescript, the question mark operator is *not* a nullable operator, it instead denotes whether something is “optional”. And there’s an important difference.

export class MyClass {
  myProperty? : string;
}

This says that the MyProperty is optional, and if no value is given, that the value will be set to “undefined”. It’s an important distinction because it’s not a “default” value, it’s “no value”. This is important because if you initialize the class like so :

let class : MyClass = { };

No error will be thrown because the property is optional.

When you instead do something like so :

export class MyClass {
  myProperty : string | null;
}

And then we initialize it the same way :

let class : MyClass = { };

We get the following error :

Property 'myProperty' is missing in type '{}' but required in type 'MyClass'

This is because while we are allowing null to be set as the value, it does not change whether a value needs to be set or not. It’s not optional. Therefore, if we use the discriminated union, we must pass in null as the initial value like so :

let class : MyClass = { myProperty : null };

Again, the most important thing about all of this is divorcing the idea that the question mark operator works the same as it does in C#. It is not a signifier of whether something can be null, it is instead used to mark something as optional. And that is an important difference.

Leave a Reply

Your email address will not be published. Required fields are marked *