Does TypeScript have dedicated functions for handling null checks?

Since TypeScript is strongly typed, using basic if () {} statements to check for null and undefined might not be sufficient.

Does TypeScript offer any dedicated functions or syntax to handle null checks more effectively?

Hey Keerti,

I hope you are doing well,

Here is your answer,

Optional Chaining (?.): Optional chaining allows you to safely access deeply nested properties without having to explicitly check each level for null or undefined. This operator returns undefined if any part of the chain is null or undefined, instead of throwing an error.

const user = { profile: { name: ‘Alice’ } }; const userName = user.profile?.name; // ‘Alice’ const userAge = user.profile?.age; // undefined

Hey Keerti,

Nullish Coalescing Operator (??): This operator provides a default value when dealing with null or undefined. It is particularly useful when you want to fall back to a default value if the expression on the left is null or undefined.

const userAge = undefined; const defaultAge = 25; const age = userAge ?? defaultAge; // 25

Hello Kirti

I hope you are doing well, Here is the Answer to your question

Type Guards: TypeScript allows you to create custom type guards to narrow down the type of a variable based on runtime checks. This helps ensure that you’re only operating on non-null values.

function isNotNull(value: T | null | undefined): value is T { return value !== null && value !== undefined; }

const value: string | null = ‘Hello’; if (isNotNull(value)) { console.log(value.length); // Safe to access ‘length’ since ‘value’ is not null or undefined }

This method help you write more robust TypeScript code by ensuring you handle null and undefined values appropriately.