TypeScript Null and Undefined|Concept & Usage Null vs Undefined

Understanding null and Undefined in TypeScript

The null and undefined in TypeScript are two distinct types that have their own unique values.

Null

It is a special value that represents “no value” or “no object”. It implies an empty or non-existent value or address.

For example:

let sample: number = null;
console.log(sample);

Output:

null

Undefined

A variable that has been declared but has not been assigned a value is undefined. It’s the default value of variables that don’t have an initial value.

For example:

let test: number;
console.log(test);

Output:

undefined

Both null and undefined are considered subtypes of all other types in TypeScript. That means you can assign null and undefined to something like a number.

TypeScript Null Coalesce

The Nullish Coalescing operator (??) in TypeScript checks if the value on its left is null or undefined. If it is, it gives you the value on its right.

If not, it gives you the value on the left. It’s a way to choose between two values when one might be null or undefined.

This can be helpful in dealing with default values or optional properties.

For example:

let website: string | undefined = undefined;
let defaultWebsite: string = "Itsourcecode";

let displayWebsite = website ?? defaultWebsite;

console.log(displayWebsite); 

As you can see in our given example above, because the website is undefined, the ?? operator returns the defaultWebsite.

If the website was not null or undefined, it would return the website.

Output:

Itsourcecode

Please note that the Nullish Coalescing operator (??) is not the same as the Logical OR operator (||).

TypeScript Null Assertion

The null assertion operator (!) in TypeScript is a postfix expression operator that can be used to assert that its operand is non-null and non-undefined in contexts where the TypeScript compiler cannot conclude that fact.

This operator tells TypeScript to trust your judgment that the value is going to be there and it won’t be null or undefined.

For example:

function getSampleValue(): string | undefined {
  return 'Itsourcecode';
}

let SampleValue = getSampleValue();
console.log('value length: ' + SampleValue!.length);

Output:

value length: 12

However, use this operator with caution. If you use it and the value is null or undefined, your program will still crash.

It’s better to handle potential null or undefined values explicitly when possible.

The null assertion operator is a last resort for cases where you’re sure the value won’t be null or undefined.

TypeScript Optional Chaining

Optional Chaining is a feature in TypeScript that lets you safely access deeply nested properties of an object without having to check for the existence of each level.

Optional Chaining uses the ?. operator.

For example:

let employee = {
  name: "Code",
  address: {
    street: "00101 Python St",
    city: "New York",
    country: "USA"
  }
};

// Using optional chaining
let street = employee?.address?.street;

// Print the street
console.log('Street: ' + street);

As you can see in our example code, employee?.address?.street will give you the street if the employee and employee.address are not null or undefined.

Meanwhile, if either is not present, it will return undefined without causing an error.

Output:

Street: 00101 Python St

Optional Chaining also extends to array items and function calls:

1. Optional element access

This lets you safely access array items:

function tryGetFirstElement<T>(arr?: T[]) {
  return arr?.[0];
}

2. Optional call

This lets you safely call functions that may not exist:

async function processTask(task: string, onError?: (error: string) => void) {
  try {
    // Simulate the execution of a task
    await new Promise((resolve) => setTimeout(resolve, 1000));
    if (Math.random() < 0.3) {
      throw new Error("Random task failure!");
    }
  } catch (error) {
    onError?.(`Error processing task "${task}": ${error.message}`);
  }
}

In these examples, arr?.[0] and log?.(…) will only be evaluated if arr and log are not null or undefined, respectively.

Remember, while Optional Chaining is a powerful tool, it should be used wisely.

Excessive usage could result in code that becomes challenging to comprehend and upkeep.

How to check null and undefined in TypeScript?

You can check if a variable is null or undefined in several ways in TypeScript.

1. Direct comparison with null or undefined

You can directly compare the variable with null or undefined using the === or == operator.

// Define the function getSomeValue
function getSomeValue(): string | null | undefined {
  // This function should return a string, null, or undefined
  // For this example, let's return a string
  return "Itsourcecode!";
}

let variable: string | null | undefined = getSomeValue();

if (variable === null) {
  console.log('variable is null');
} else if (variable === undefined) {
  console.log('variable is undefined');
} else {
  console.log('variable is neither null nor undefined, it is: ' + variable);
}

Output:

variable is neither null nor undefined, it is: Itsourcecode!

2. Truthy/Falsy check

In JavaScript and TypeScript, null and undefined are falsy values.

You can use this to check if a variable is null or undefined:

let variable: string | null | undefined = getSomeValue();

if (variable) {
  console.log('variable is neither null nor undefined');
} else {
  console.log('variable is either null or undefined');
}

3. Type guards

TypeScript has type guards that check if a variable is null or undefined:

let variable: string | null | undefined = getSomeValue();

if (typeof variable === 'string') {
  console.log('variable is a string');
} else {
  console.log('variable is either null or undefined');
}

4. Optional chaining (?.) and Nullish coalescing (??) operators

These operators can be used to provide default values when dealing with null or undefined:

let variable: string | null | undefined = getSomeValue();

// If variable is null or undefined, it will print 'default value'
console.log(variable ?? 'default value');

Remember, it’s a good practice to handle potential null or undefined values explicitly when possible to prevent runtime errors.

The TypeScript compiler can help with this if you enable strict null checks with the —strictNullChecks flag.

Conclusion

That concludes our exploration of Null and Undefined in TypeScript. We’ve delved into these two distinct types, each possessing its own unique value.

Through this discussion, we’ve shed light on the nuances and usage of Null and Undefined in TypeScript, aiming to provide a comprehensive understanding of these concepts.

I hope that this article helps you understand TypeScript Null and Undefined.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment