Optional class members in Typescript

Optional class properties was added as a feature in Typescript 2.0.

In this example, property b is optional:

class Bar {
  a: number;
  b?: number;
}

Typescript 2.0 release notes - Optional class properties


The following works in TypeScript 3.x:

class Foo {
  a?: string;
  b?: string;
  c: number = 123;
}

Note that you need to initialise any members that are not optional (either inline as shown or in the constructor).


In some use cases you can accomplish it with Parameter properties:

class Test {
    constructor(public a: string, public b: string, public c?: string)
    {
    }
}

var test = new Test('foo', 'bar');

playground

Tags:

Typescript