Property removals in TypeScript

A quick note about how to easily go from a broader type to a narrower one in TypeScript.

Suppose you have the following two interfaces:

interface ABC {
  a: number;
  b: string;
  c: boolean;
}

interface AB {
  a: number;
  b: string;
}

We want to convert a var from ABC to AB. Although ABC meets all the constraints of AB, the additional excess properties sometimes break things and TypeScript will, sometimes, complain about them.

So we could just do this:

declare var myVar: ABC;
delete myVar.c;

But that’s not really desirable because, assuming TypeScript even lets you do that, you’re mutating an existing typed object. myVar is still typed as ABC, even though it no longer has a c property.

I used to frequently write code that cloned myVar, deleted the extra property, and then typecast the clone to a new interface. But with the introduction of destructuring and spread operator support in TypeScript 2.1, it’s actually quite simple now:

let { c, ...newVar } = myVar

Tada! newVar is created without the c property, and TypeScript recognizes it.

Comments