35

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

 4 years ago
source link: https://www.tuicool.com/articles/nqQnAra
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 1contains 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK