Typescript - Tips & Tricks - Non-null assertion operator

In some cases, you have a field that you initialize in a method, and if you follow the flow of the...

#typescript#webdev
Luca Del PuppoLuca Del Puppo
Article Series · Part 13 of 21TypeScript - Tips & Tricks
View full series (21)
  1. #12Previous
    Tuple
  2. #13Reading now
    Non-null assertion operator
  3. #14Up next
    Never type
Browse all 21 parts in this series
  1. #1typeof
  2. #2Literal Types
  3. #3keyof
  4. #4Union and Intersection
  5. #5Overloaded Functions
  6. #6this parameter
  7. #7any vs. unknown
  8. #8Optional modifier
  9. #9Index Signature
  10. #10readonly modifier
  11. #11Readonly Array
  12. #12Tuple
  13. #13Non-null assertion operatorCurrent
  14. #14Never type
  15. #15Assert Function
  16. #16Type Guard
  17. #17Conditional Type
  18. #18infer keyword
  19. #19Mapped Types
  20. #20Advanced Types
  21. #21Rest Parameters & Rest Arguments

In some cases, you have a field that you initialize in a method, and if you follow the flow of the code you are sure that this field is initialized but typescript doesn’t understand it. An example

type Person = {
  name: string;
};

let person: Person;

function initialize() {
  person = { name: "name" };
}

initialize();
console.log("Hello", person.name); // Variable 'person' is used before being assigned.

In this case, you can see how the typescript compiler doesn’t understand that the “person” field isn’t null but it’s initialized. To resolve this problem, the typescript language exposes us the “Non-null assertion operation”(!). This operator says to the compiler that the field isn’t null or undefined but it’s defined. The previous example can be reviewed in this way

type Person = {
  name: string;
};

let person: Person;

function initialize() {
  person = { name: "name" };
}

initialize();
console.log("Hello", person!.name);

As you can see, in this case, the code doesn’t have errors and the compilation ends with success.

That’s all for today! Bye-bye guys!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.