Skip to content

Instantly share code, notes, and snippets.

@manuelaplesa96
Created May 23, 2024 05:54
Show Gist options
  • Save manuelaplesa96/cebd46b0389e77b02e13ad5f62131eb1 to your computer and use it in GitHub Desktop.
Save manuelaplesa96/cebd46b0389e77b02e13ad5f62131eb1 to your computer and use it in GitHub Desktop.
The gist that shows an example of the null safety mechanism in the TypeScript programming language.
const car1 = {
brand: ‘carBrand1’
color: ‘red’
};
const car2 = undefined;
// it logs a value
console.log(car1.color);
/*
if we do not use null safety mechanism next part of the code will throw Uncaught
ReferenceError: car2 is not defined
*/
console.log(car2.color);
/*
if we use null safety mechanism ?. we will avoid throwing an error and program
will continue to work - it logs undefined
*/
console.log(car2?.color)
/*
like in all other programming languages which does not have null safety mechanism,
we can also write last part of the code in the different, more complicated, way
and add possibility to forget some of the cases which then can cause ReferenceError
*/
console.log(car2 !== undefined ?? car2 !== null ? car2.color : undefined)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment