Optional class properties
Optional properties and methods can now be declared in classes, similar to what is already permitted in interfaces.
Example
class Bar {
a: number;
b?: number;
f() {
return 1;
}
g?(): number; // Body of optional method can be omitted
h?() {
return 2;
}
}
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:
function test(x: Bar) {
x.a; // number
x.b; // number | undefined
x.f; // () => number
x.g; // (() => number) | undefined
let f1 = x.f(); // number
let g1 = x.g && x.g(); // number | undefined
let g2 = x.g ? x.g() : 0; // number
}