这假设strictNullChecks为true。
如果几种方法依赖于一个不为空的值,则每个方法都应检查该值,如果为空,则抛出异常。将空检查提取到辅助方法中,而不是在各处复制它,将是很好的。但是,如果这样做,就无法对每种方法中的值进行类型检查。
例如,不提取空检查:
class FooClass {
public foo: number | null = null;
public thisNeedsFooToNotBeNull(): void {
if (this.foo === null) {
throw new Error('foo should not be null');
}
doStuff(this.foo);
}
}
function doStuff(foo: number) {
console.log(`foo is ${foo}`);
}
带有提取:
class FooClass {
public foo: number | null = null;
private validateFoo(): void {
if (this.foo === null) {
throw new Error('foo should not be null');
}
}
public thisNeedsFooToNotBeNull(): void {
this.validateFoo();
doStuff(this.foo);
}
}
function doStuff(foo: number) {
console.log(`foo is ${foo}`);
}
在第二个版本中,我们在doStuff(this.foo);
行上收到TypeScript错误,说:
Argument of type 'number | null' is not assignable to parameter of type 'number'.
Type 'null' is not assignable to type 'number' ts(2345)
有没有办法让TypeScript处理这种类型检查提取?
当TypeScript 3.7推出时,它将具有the asserts
modifier,它允许您将asserts
-返回函数标记为类型断言,类似于void
允许您将user-defined type guards-返回函数标记为类型检查。
很快(或者如果您现在安装boolean
,现在就应该可以这样注释typescript@next
了:
validateFoo()
[这里是说,对private validateFoo(): asserts this is { foo: number } {
if (this.foo === null) {
throw new Error('foo should not be null')
}
}
的调用返回了validateFoo()
,这意味着如果asserts this is { foo: number }
完全返回,它将使validateFoo()
的范围从this
缩小(其FooClass
属性为foo
)到number | null
,表示this & { foo: number }
属性将不是foo
。
您的其余代码应按预期编译:
null
希望有所帮助;祝你好运!
public thisNeedsFooToNotBeNull(): void {
this.validateFoo();
doStuff(this.foo); // no error now
}
您可以使用Link to code(它只是non-null assertion operator):
!