The Startup
Published in

The Startup

Tech: Cool TypeScript Operators You Might Not Know

These shorthand operators are truly amazing!!!

In recent years, TypeScript (TS) has become one of the most popular programming languages among web community. It is basically a strictly typed version of JavaScript and so much more. Thanks to its strong type checking, inline documentation and great community support; TS has been adopted heavily by major JavaScript frameworks like Angular, React and Vue. In this article, we will go through several handy TS operators that can help you reduce boilerplate and make your codes look cleaner and easy to read.

Note that different operators demonstrated below might only be available at specific TS version.

Template Strings — TS v1.4

When building web pages you often need to construct a string from string literals (string constants) along with one or many arbitrary expressions (variable strings). Since version 1.4, TS has supported ES6 template strings to help decompose string objects easily.

// With Template Strings
const person = {name: 'John', age: 15};
const greeting =
`Hello, ${person.name}. You are ${person.age} years old`;

// W/o Template Strings
const person = {name: 'John', age: 15};
const greeting =
"Hello, " + person.name + ". You are " + person.age + "years old";

Conditional (Ternary) Operator

If you come from JavaScript background, obviously you are familiar with conditional or ternary operator. It is a short way to write an if-else statement with a goal of having all the logic in one line.

// With Ternary Operator
const hour = 20;
const dayStatus = hour < 18 ? 'day' : 'night';

// With if-else
const hour = 20;
let dayStatus = '';
if (hour < 18) {
dayStatus = 'day';
} else {
dayStatus = 'night';
}

In addition, you can also call a function/method inside the ternary operator. Keep in mind that the function must return a value in order for the operator to work without error.

const test = 1;
const result = test === 1 ? doTestA() : 0;
or
const result = test === 1 ? 0 : doTestB();

Optional Chaining — TS v3.7

One of the most annoying bugs in JS is null pointer exception, an exception occurred when the code accesses a property of a null object. To make sure developers safely check for null before accessing its property, TS introduced a brand new operator in v 3.7 called Optional Chaining. By using this operator, it will stop executing some expressions if we encounter a null or undefined object.

// With optional chaining
const x = foo?.bar.baz();
// W/o optional chaining
const x =
foo === null || foo === undefined ? undefined : foo.bar.baz();

Optional Chaining also works with accessing array’s element using index

// With optional chaining
const x = arr?.[0];
// W/o optional chaining
const x =
arr === null || arr === undefined ? undefined : arr[0];

Nullish Coalescing — TS v3.7

If you are still being impressed by how convenient it is to use optional chaining for null check…hold your beer 🍻… there’s another awesome operator that goes hand-in-hand with optional chaining called Nullish Coalescing. Not only does this operator check for null object it also lets us define a default value when it sees null or undefined references.

// With Nullish Coalescing
const x = foo ?? 0;

// W/o Nullish Coalescing
const x = foo !== null && foo !== undefined ? foo : 0;

Short-Circuiting Assignment Operators

1. Basic Operators

The concept of Short-Circuiting Assignment operators in TS have already existed in JavaScript and other languages. Without further explanations, let’s review some basic operators you might have seen before.

// Addition 
a += b; // a = a + b
// Subtraction
a -= b; // a = a - b
// Multiplication
a *= b; // a = a * b
// Division
a /= b; // a = a / b
// Exponentiation
a **= b; // a = a ** b
// Left Bit Shift
a <<= b; // a = a << b

2. Three new operators — TS v4.0

In v 4.0, TS added another 3 to the list of short-circuiting assignment operators:

  • logical and (&&),
  • logical or (||),
  • nullish coaleascing (??)
// logical and (&&)
a &&= b // a = a && b
// logical or (||)
a ||= b // a = a || b
// nullish coaleascing (??)
a ??= b // a = a ?? b

One of the advantages of using these kinds of operators is that you are able to initialize a variable on the fly. Take a look at an example below

let arr: string[]; 
(arr ??= []).push("lala");
// same as
(arr ?? (arr = [])).push("lala");

Reference

https://www.typescriptlang.org/docs/handbook/

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Kubeflow 0.2 Offers New Components and Simplified Setup

How to Activate Namecheap SSL Certificate

namecheap ssl certificate

How to Build Java Applications Today: June 7, 2021

S3 to ClickHouse

Learn to Code, Part 2: Telling Blue Dog’s Story, Using Scratch

Essential SAFe: Building a Strong Foundation

The one where we explore a new way of writing certain user stories

Incidents in SaaS: Causes and Mitigation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Khoi Bui

Khoi Bui

Front End architect, opensource contributor and investment enthusiast. New content posted every week.

More from Medium

The Most Important Assertions in Jest, React Testing Library Tests

Animating Styled Components using Style Objects or Tagged Template Literals

useGet/Post React Custom hook

React 18. What’s new?