Open In App

TypeScript Non-null Assertion Operator (Postfix !) Type

TypeScript non-null assertion operator (!) is used to assert that a value is non-null and non-undefined, even when TypeScript’s strict null checks are enabled. This operator tells TypeScript to treat the expression as if it’s guaranteed to have a value, eliminating compile-time null and undefined checks.

Syntax

const nonNullValue: Type = value!;

Parameters

Example 1: In this example,






function greetUser(name: string | null) {
  
    // Using the non-null assertion operator 
    // to ensure 'name' is not null
    const formattedName: string = name!;
    console.log(
        `Hello, ${formattedName || 'GeeksforGeeks'}!`);
}
  
greetUser("Akshit"); // Output: Hello, Akshit!
greetUser(null); // Output: Hello, GeeksforGeeks!

Output:



Example 2: In this example:We define a User type representing a user object with potentially nullable properties. We create a user object with a name property (non-nullable) and an email property (nullable). We use the non-null assertion operator ! to assert that the email property is non-null when accessing it. This is done because TypeScript considers user.email to be potentially undefined due to the email? property definition in the User type.

We then log both the userName and userEmail variables. TypeScript will not raise any errors related to nullability because of the non-null assertion operator.




type User = {
    name: string;
    email?: string;
};
  
// Create a user object with nullable 
// properties
const user: User = {
    name: "GeeksforGeeks",
    // Email is intentionally omitted
};
  
// Use the non-null assertion operator 
// to access properties
// No assertion needed, name is guaranteed
const userName: string = user.name; 
  
// Use ! to assert that email is non-null
const userEmail: string = user.email!; 
  
console.log(`User Name: ${userName}`);
console.log(`User Email: ${userEmail}`);

Output:

Reference: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator


Article Tags :