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

Advertisements

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.

>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();

Leave a Reply Cancel reply