How to Use Exclamation Mark (!) in TypeScript

The exclamation mark(!) is a “non-null assertion operator” that is used to “remove null and undefined values“.

By using the “! operator”, you’re telling TypeScript to trust that the value is present, and it should not raise a type error. It’s a way of overriding TypeScript’s strict null checks.

However, using the non-null assertion operator comes with a risk: if the value is null or undefined, you might encounter runtime errors. Therefore, using this operator only when you are confident that the value exists or when you have checks in place to handle null or undefined values is recommended.

Example 1: Usage of Exclamation Mark (!)

type User = {
  name: string;
  age?: number;
}

The age property is optional, which means it could be undefined. If you try to access it directly, TypeScript might complain, depending on your configuration:

function printAge(user: User) {
  console.log(user.age.toFixed(2));
}

However, if you’re sure that age exists in a specific context (maybe because of some runtime checks or logic not visible to TypeScript), you can use the ! operator to assert that it’s not null or undefined:

function printAge(user: User) {
  console.log(user.age!.toFixed(2));
}

By adding the ! after user.age, you are telling TypeScript: “I’m sure this is not null or undefined; trust me on this.”

Example 2: Using a variable of type string | null for a function that accepts a string

If you have a variable of type string | null and want to pass it to a function that expects a string, you will run into a type error. This is because the function is expecting a string, and null is not a valid value for a string.

function fetchUserName() {
}

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

const userName: string | null = fetchUserName();

// This will cause a TypeScript error
greet(userName); 

If you are certain, the value won’t be null at the point of the function call.

function fetchUserName() {
  return "Niva"
}

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

const userName: string | null = fetchUserName();

// This will cause a TypeScript error
greet(userName!); 

Output

Using a variable of type string | null for a function that accepts a string

I hope this helps!