TypeScript 3.7: A Game-Changing Release
Saying Goodbye to Null Checks
One of the most significant pain points in the JavaScript/TypeScript world is continuously checking variables or expressions for null or undefined. But those days are behind us now. With optional chaining, we can finally stop writing unnecessary code and focus on what really matters.
Optional Chaining: A New Era
Optional chaining allows us to access properties, methods, or subscripts on an optional value without having to worry about null or undefined. By placing a question mark (?) after the optional property value, we can force the unwrapping of its value. If a null or undefined value is found, undefined is returned.
let person = { name: 'John', address: { street: '123 Main St' } };
console.log(person.address?.street); // outputs: '123 Main St'
console.log(person.address?.city); // outputs: undefined
Deeply Nested Objects, No Problem!
Dealing with deeply nested objects just got a whole lot easier. With optional chaining, we can access properties and methods without having to write lengthy, error-prone code. This feature is a game-changer, and we can’t wait to see the impact it will have on our development workflow.
let person = { name: 'John', address: { street: '123 Main St', coordinates: { lat: 37.7749, lng: -122.4194 } } };
console.log(person.address?.coordinates?.lat); // outputs: 37.7749
console.log(person.address?.coordinates?.altitude); // outputs: undefined
Accessing Subscripts Made Easy
Optional chaining also allows us to access subscripts on an optional value. By placing the question mark before the subscript’s brackets, we can check whether the subscript call is successful. This feature is particularly useful when working with arrays and objects.
let arr = [1, 2, 3];
console.log(arr?.[0]); // outputs: 1
console.log(arr?.[5]); // outputs: undefined
let obj = { a: 1, b: 2 };
console.log(obj?.a); // outputs: 1
console.log(obj?.c); // outputs: undefined
The Null Coalescing Operator: A New Best Friend
Another feature that’s got us excited is the null coalescing operator (??). This operator simplifies checking for null or undefined values, making our code more concise and efficient. We’ll no longer have to worry about JavaScript’s truthy and falsy shenanigans.
let name = 'John';
let greeting = name?? 'Unknown';
console.log(greeting); // outputs: 'John'
let age = null;
let defaultAge = age?? 25;
console.log(defaultAge); // outputs: 25
A New Era of Efficient Coding
With TypeScript 3.7, we’ll be writing significantly less code that checks for the existence of things. This update is a massive step forward, and we can’t contain our excitement. The days of tedious null checks are behind us, and we’re ready to take our coding skills to the next level.