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
I hope this helps!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.