Paul Cowan Contract software developer

New in TypeScript 3.7

Spoiler alert: Optional chaining and the null coalescing operator are game-changers

3 min read 847

I think the TypeScript 3.7 release is enormous. I have waited a very, very long time to have optional chaining having tasted it briefly on a C# contract a few years ago.

What problem does it solve?

One of the most significant pain points that most of us have in the JavaScript/TypeScript world is continuously checking variables or expressions for null or undefined. The example below is TypeScript 3.7 and illustrates what a game-changer this release is. We can finally drastically stop the amount of nonsense code we have to write with the new feature.

class Student {
  constructor(public name: string) {}

  discipline?: Discipline;
  
  printDetails() {
    return `
      name: ${this.name}
      discipline: this.discipline?.name || 'Not set';
    `;
  }
}

class Discipline {
  student?: Student;

  constructor(public name: string) { }
}

class College {
  constructor(public name: string) { }

  disciplines?: Discipline[];
}

class City {
  constructor(public name: string) { }

  college?: College;
}


class University {
  constructor(public name: string) { }

  city?: City;

  get college(): College | undefined {
    return this?.city?.college;
  }

  addDisciplines(...disciplines: Discipline[]) {
    if (!this.city?.college?.disciplines) {
      return;
    }

    this.city.college.disciplines.push(...disciplines)
  }
}

const university = new University("Queen's University Belfast");
const city = new City("Belfast");
const computerScience = new Discipline("Computer Science");
const economics = new Discipline("Economics");
const college = new College("Da College");
const student = new Student("Brian Cant");

university.city = city;
university.city.college;

university.addDisciplines(computerScience, economics);

const firstStudent = university.city?.college?.disciplines?.[0]?.student; // Student | undefined

console.log(firstStudent?.printDetails())

Here is a playground with a working example of the above code snippet.

Line 1 contains a Student class definition which contains an optional discipline property that might have an undefined or null value. A printDetails method exists on line 6 that involves access with an optional property.

printDetails() {
  return `
    name: ${this.name}
    discipline: this.discipline?.name || 'Not set';
  `;
}

You specify optional chaining by placing a ? question mark after the optional property value on which you wish to call the property, method or even subscript (more on this later) to force the unwrapping of its value. If during the unwrapping of the property or method a null value or an undefined value is found, undefined is returned. undefined is always returned no matter if the underlying value is null or undefined.

Below is some of the horrible code we would tediously write before this exquisite release.

printDetails() {
  return `
    name: ${this.name}
    discipline: this.discipline && this.discipline.name ? this.discipline.name : 'Not set';
  `;
}

Where optional chaining glistens is when dealing with deeply nested objects on line 3 of the code example below or line 63 of the first code example:

university.addDisciplines(computerScience, economics);

const firstStudent = university.city?.college?.disciplines?.[0]?.student; // Student | undefined

console.log(firstStudent?.printDetails())

We would previously have to do some pretty disgusting things to access such a deep hierarchy, but we can now optionally chain our way to a much better existence with TypeScript 3.7.

Accessing subscripts through optional chaining

You can use optional chaining to try to retrieve a value from a subscript on an optional value and to check whether that subscript call is successful.

const firstStudent = university.city?.college?.disciplines?.[0]?.student;

Instances of the Discipline class can have an array of students. When you access a subscript on an optional value through optional chaining, you place the question mark before the subscript’s brackets, not after. The optional chaining question mark always follows immediately after the part of the expression that is optional.

I think this is massive, we will write significantly less code that checks for the existence of things. I cannot contain my excitement at this release.

The null coalescing operator

Another feature I have experienced previously in C# is the null coalescing operator (??) that simplifies checking for null or undefined values.

const a: number | null = null;
const b = a ?? 42;

console.log(b);  // 42

What about ||?

The first time I saw this in TypeScript, I shouted ‘what about ||?’ Below is the same example with the same result.

const a: number | null = null;
const b = a || 42;

console.log(b);  // 42

Where this example falls apart is with JavaScript’s truthy and falsy shenanigans.

const a: number | null = 0;
const b = a || 42;

console.log(b);  // 42

Unfortunately 0 returns false when used in an expression with JavaScript so 42 will get to the console which is incorrect.

The coalescing operator comes to the rescue in this situation.

const a: number | null = 0;
const b = a ?? 42;

console.log(b);  // 0

I am going to stop using the shortcircuit or || operator when TypeScript 3.7 gets released and instead use the beautiful ?? operator.

Game changed

I have waited a long time for these changes, and I think the TypeScript official announcement does its usual job of underselling the great new features.

I also hate the code examples they use:

// Before
if (foo && foo.bar && foo.bar.baz) {
    // ...
}

// After-ish
if (foo?.bar?.baz) {
    // ...
}

I think this illustrates the disconnect between the real world and the TypeScript developers. foo, bar ,and baz are just about the worst examples to use for anything. I cannot think of anything tangible with these made up properties.

I think there should be much more made of this release. It will make writing TypeScript significantly less annoying.

Please leave feedback on the comments below.

Paul Cowan Contract software developer

6 Replies to “New in TypeScript 3.7”

  1. So typescript is going to have pretty much every feature C# has. (what a coincidence, they’re designed by the same person)

  2. The optional chaining operator just tells me that I am going to show up at client sites where every single dot in the application is preceded by a question mark, the same way that async permeates through the code.

    It tells me that nobody is actually going to know anything about the data that runs through the system, and it’s going to hide bugs that are ridiculous to solve, because they could have happened at any `?.` upstream from where your data was supposed to be.
    Moreover, this affects all downstream systems, as well.

    I’m not saying that 10,000 null checks is good, either. What I am saying is that we are programming backwards. What I am saying is that we should have systems that are hermetically sealed, and operate only on types that are known, not types where every member is optional/nullable. If you can’t build an instance of a type with the pieces you have been given (plus any reasonable defaults), then you should take a different path in code, rather than passing in a tree that is garnished with nulls.

    The invention/inclusion of null in programming languages was Tony Hoare’s billion dollar mistake, and instead of thinking about how we can program without it, we are making it easier to make everything null, at all times, without crashing.

    However, the null coalescing operator is a good tool for building those known and trusted data types from untrusted data sources (server responses, database fields, localStorage, user input), *if* the field you are settling has a valid default/empty/identity state. Optional chaining would be fine to use in the case where you were grabbing an expected value from an unknown data source, and using the coalescing operator to set the default, when building a closed system of well-defined types… but we all know that isn’t how it’s going to be used.

  3. Personally I think the worst thing about their announcement blog post is the dubious formatting of ternary operators. I mean, everybody knows that you’re supposed to format them
    “`
    var result = condition
    ? first_expression()
    : second_expression()
    “`

Leave a Reply