Optional class properties

Optional properties and methods can now be declared in classes, similar to what is already permitted in interfaces.

Example

  1. class Bar {
  2. a: number;
  3. b?: number;
  4. f() {
  5. return 1;
  6. }
  7. g?(): number; // Body of optional method can be omitted
  8. h?() {
  9. return 2;
  10. }
  11. }

When compiled in —strictNullChecks mode, optional properties and methods automatically have undefined included in their type. Thus, the b property above is of type number | undefined and the g method above is of type (() => number) | undefined.Type guards can be used to strip away the undefined part of the type:

  1. function test(x: Bar) {
  2. x.a; // number
  3. x.b; // number | undefined
  4. x.f; // () => number
  5. x.g; // (() => number) | undefined
  6. let f1 = x.f(); // number
  7. let g1 = x.g && x.g(); // number | undefined
  8. let g2 = x.g ? x.g() : 0; // number
  9. }