Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When does optional (?) mean undefinable or nullable in TypeScript?

Is the optional notation (?) describe a type as being any | undefined or any | null or either? In the following, it seems it is for both but I could not find if this is officially the case:

type MyType = {
  prop1?: string;
  prop2: string | null;
}

const something: MyType = { prop2: null };
something.prop1?.toString();
something.prop2?.toString();

Does optional really mean any | null | undefined? By any I mean generically any type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

? has multiple meanings in typescript (and in javascript for that matter). In a typescript type, ? means the property might be undefined. null plays no role in this. The following line is an example of ? in a type:

type MyType = {
  prop1?: string; // similar to prop1: string | undefined
}

In javascript code (and thus typescript code inherits this syntax), ?. is the optional chaining operator. It’s similar to accessing a property via ., except it will short circuit evaluation if the value is null or undefined. Note that this is never a ? on its own, it’s always combined with a ., and it’s always in code not types.

The following is an example of ?. in code:

something.prop1?.toString();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading