In TypeScript with strict: true
config, consider the following scenario:
export class A {
a?: string;
b?: number;
init() {
this.a = "";
this.b = 0;
}
opA() {
this.requireInit();
const something = this.a.length; // Error here
}
opB() {
this.requireInit();
const something = this.b.toString(); // Error here
}
private requireInit() {
if (this.a === undefined || this.b === undefined) {
throw new Error("Call init before using this method");
}
}
}
Is there a way to mark requireInit
method that after calling that method, a
and b
members is not undefined anymore so I do not have to use !
in every method? In C# there is a similar Attribute called MemberNotNull
.
CodePudding user response:
Making requireInit
into an assertion function that asserts that its this
definitely has those properties will do the trick.
class A {
a?: string;
b?: number;
init() {
this.a = "";
this.b = 0;
}
opA() {
this.requireInit();
const something = this.a.length; // OK now
}
opB() {
this.requireInit();
const something = this.b.toString(); // OK now
}
private requireInit(): asserts this is { a: string, b: number } {
if (this.a === undefined || this.b === undefined) {
throw new Error("Call init before using this method");
}
}
}