在 TypeScript 中是否有任何 "annotation" 方法来指示变量在退出后不会为空?
In TypeScript is there any "annotation" for methods to indicate a variable won't be null after exiting it?
在带有 strict: true
配置的 TypeScript 中,考虑以下场景:
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");
}
}
}
有没有办法标记 requireInit
方法,在调用该方法后,a
和 b
成员不再是未定义的,所以我不必使用 !
在每一个方法?在 C# 中有一个类似的属性,叫做 MemberNotNull
.
将 requireInit
变成一个断言其 this
肯定具有这些属性的 assertion function 就可以了。
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");
}
}
}
在带有 strict: true
配置的 TypeScript 中,考虑以下场景:
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");
}
}
}
有没有办法标记 requireInit
方法,在调用该方法后,a
和 b
成员不再是未定义的,所以我不必使用 !
在每一个方法?在 C# 中有一个类似的属性,叫做 MemberNotNull
.
将 requireInit
变成一个断言其 this
肯定具有这些属性的 assertion function 就可以了。
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");
}
}
}