Saturday, May 24, 2025

Understanding TypeScript Operators: !, ?, ??, and ?. Explained

In this example we will explore how to use TypeScript Operators: !, ?, ??, and ?. with simple example in typescript project as well playwright with typescript binding.

Understanding TypeScript Operators: !, ?, ??, and ?. Explained


! — Non-null Assertion Operator

Used to assert that a value is not null or undefined.

let maybeString: string | undefined = "Hello";
console.log(maybeString!.length); // Tells TypeScript: "Trust me, it's not undefined"


? — Optional Property or Parameter

Used in object types or function parameters to indicate something is optional.

interface User {
  name: string;
  age?: number; // Optional property
}

function greet(user: User) {
  console.log(`Hello, ${user.name}`);
}

?? — Nullish Coalescing Operator

Returns the right-hand operand when the left is null or undefined.

let input: string | null = null;
let result = input ?? "Default Value";
console.log(result); // "Default Value"

?. — Optional Chaining

Used to safely access deeply nested properties without throwing an error if something is null or undefined.


Example -1 

let user: { profile?: { email?: string } } = {};
let email = user.profile?.email ?? "No email found";
console.log(email); // "No email found"

Example -2 

const user = {
  name: "Alice",
  address: {
    city: "Wonderland",
    postalCode: "12345"
  }
};

console.log(user.address?.city);        // "Wonderland"
console.log(user.profile?.bio);         // undefined (no error)

This is a simple example to understand !, ?, ??, and ? operator in typescript with simple example.



No comments:

Post a Comment