How to Use the Exclamation Mark in TypeScript?

In this tutorial, I will explain the use of the exclamation mark in TypeScript, also known as the non-null assertion operator. Recently, while working on a project for a client in New York, I encountered a situation where I needed to assure the TypeScript compiler that certain variables were not null or undefined. This tutorial will help you understand when and how to use the exclamation mark effectively in your TypeScript projects.

To use the exclamation mark in TypeScript, place it after a variable to assert that it is neither null nor undefined. This operator, known as the non-null assertion operator, informs the TypeScript compiler that the variable is safe to use without additional null checks. For example, element!.value tells the compiler that element is definitely not null or undefined, allowing you to bypass strict type checks and avoid potential runtime errors.

What is the Exclamation Mark in TypeScript?

The exclamation mark (!) in TypeScript is used as a non-null assertion operator. It tells the TypeScript compiler that a particular variable cannot be null or undefined, even if the compiler cannot deduce that from the code. This is particularly useful in scenarios where you are certain about the non-nullability of a variable, but the compiler isn’t.

Syntax and Basic Example

The syntax for using the exclamation mark is simple. You place it immediately after a variable or property access to assert that it is non-null or non-undefined.

Here is the syntax:

let element = document.getElementById('myElement')!;
element.style.color = 'blue';

In this example, document.getElementById('myElement') might return null if the element is not found. By appending !, we assert that element is not null, allowing us to safely access its style property.

Check out How to Use Try Catch in TypeScript?

TypeScript Exclamation Mark Examples

Now, let me show you a few examples of TypeScript Exclamation Mark.

Example 1: Accessing DOM Elements

When working with DOM elements, TypeScript often flags potential null values. Here’s how you can handle this using an exclamation mark.

function updateUserProfile() {
  const userNameElement = document.getElementById('userName');
  // Non-null assertion
  userNameElement!.innerText = 'John Doe';
}

Example 2: Working with Optional Properties

Consider an application for a San Francisco-based company that manages employee records. Each employee might have an optional middleName property:

interface Employee {
  firstName: string;
  lastName: string;
  middleName?: string;
}

function getFullName(employee: Employee) {
  // Non-null assertion
  return `${employee.firstName} ${employee.middleName!} ${employee.lastName}`;
}

const employee: Employee = { firstName: 'Jane', lastName: 'Doe', middleName: 'A.' };
console.log(getFullName(employee)); // Output: Jane A. Doe

Here is the exact output you can see in the screenshot below:

typescript exclamation mark

Read TypeScript Interview Questions and Answers

Example 3: Handling API Responses

When dealing with API responses, you might encounter nullable fields. For example, you’re developing an application for a Miami-based travel agency that fetches flight details:

interface FlightDetails {
  flightNumber: string;
  departureTime: string | null;
}

function displayFlightDetails(details: FlightDetails) {
  const flightInfoElement = document.getElementById('flightInfo');
  // Non-null assertion
  flightInfoElement!.innerText = `Flight Number: ${details.flightNumber}, Departure Time: ${details.departureTime!}`;
}

Check out How to Handle Catch Error Types in TypeScript?

TypeScript Exclamation Mark After Variable

Let me show you how to use the exclamation mark after a variable in TypeScript. It is particularly useful when dealing with DOM elements or other APIs that might return null.

Here is an example.

Example: DOM Manipulation

const button = document.querySelector('button')!;
button.addEventListener('click', () => {
  console.log('Button clicked!');
});

Here, document.querySelector('button') may return null if no button is found. The ! operator asserts that button is not null.

TypeScript Exclamation Mark in Variable Declaration

In TypeScript, you can also use the exclamation mark in variable declarations to indicate that a variable will not be null or undefined after its initial assignment.

Example: Class Properties

Here is an example to understand this.

class User {
  name!: string;
  constructor(name: string) {
    this.name = name;
  }
}

In this example, the name property is declared with !, telling TypeScript that it will be initialized later, thus avoiding the strictPropertyInitialization error.

Check out How to Check TypeScript Version?

TypeScript Double Exclamation Mark After Variable Declaration

The double exclamation mark (!!) is not a TypeScript-specific feature but rather a JavaScript idiom used to convert a value to a boolean.

Example: Boolean Conversion

Here is an example.

let value: any = "Hello, World!";
let isNonEmptyString: boolean = !!value;
console.log(isNonEmptyString); // true

Here, !!value converts value to a boolean, which is true if value is truth.

Here is the exact output in the screenshot below:

typescript double exclamation mark after variable declaration

Check out Difference Between == and === in TypeScript

TypeScript Exclamation Mark vs Question Mark

The exclamation mark (!) and question mark (?) serve different purposes in TypeScript. While ! is a non-null assertion operator, ? is used for optional chaining and optional properties.

Example: Optional Chaining

Here is an example.

let user: { name?: string } = {};
console.log(user.name?.toUpperCase()); // undefined

In this example, user.name?.toUpperCase() safely accesses name only if name is defined.

TypeScript Exclamation Mark Before Variable

Using an exclamation mark before a variable is not common in TypeScript. However, in JavaScript, it is used to negate a boolean value.

Example: Boolean Negation

Here is an example.

let isLoggedIn = false;
if (!isLoggedIn) {
  console.log('User is not logged in.');
}

Here is the exact output:

TypeScript Exclamation Mark Before Variable

TypeScript Exclamation Mark Before Dot

The exclamation mark before a dot is not a recognized syntax in TypeScript. However, it can be combined with optional chaining to assert non-null values.

Let me show you an example.

Example: Combining Non-Null Assertion with Optional Chaining

let user: { name?: string } = { name: "John" };
console.log(user.name!.toUpperCase()); // JOHN

Here, user.name! asserts that name is not null or undefined before calling toUpperCase().

Check out How to Run TypeScript Files?

TypeScript Exclamation Mark in Type Definition

In type definitions, the exclamation mark is not typically used. Instead, TypeScript uses ? to denote optional properties.

Example: Type Definition with Optional Properties

interface User {
  name: string;
  age?: number;
}

In this example, age is an optional property, meaning it may or may not be present on objects of type User.

Conclusion

The exclamation mark in TypeScript helps to assert non-nullability in scenarios where the compiler is unsure. I have explained how to use it here with various examples.

You may also like: