Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The guarded clause is a syntax used in TypeScript to ensure that a variable is defined before accessing its properties or methods. In the case where the TS object is potentially undefined, the guarded clause is used to check if the object is defined. If the object is defined, the code inside the guarded clause is executed, and if the object is undefined, the code inside the guarded clause is skipped.

Here is an example of how the guarded clause is used when the TS object is potentially undefined:

let obj: SomeObject | undefined = undefined;

if (obj) {
  console.log(obj.property); // This code will not execute as obj is undefined
}

// Using the guarded clause to check if obj is defined
if (obj !== undefined) {
  console.log(obj.property); // This code will also not execute as obj is undefined
}

// Using the guarded clause to check if obj is defined and then accessing its property
if (obj?.property) {
  console.log(obj.property); // This code will not execute as obj is undefined
}

In the last example, the ?. syntax is used which ensures that the property is only accessed if the object is defined.