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