这是可能有不限制类型if的函数调用never回报例如undefined像assert在打字稿?
示例代码:
interface Foo { bar(): void }
function getFoo(): Foo | undefined { }
function test() {
const foo = someService.getFoo();
assert(foo);
if (!foo) { // now mandatory because without this foo may be still undefined even if assert protects us from this
return;
}
foo.bar(); // , here foo may be undefined
}
Run Code Online (Sandbox Code Playgroud)
我希望能够写assert在这样的方式,我可以跳过下面的if (!foo)条款,并有foo限于普通型Foo。
这是可能的打字稿?
我试过never为抛出的类型添加重载:
function assertGuard(v: undefined …Run Code Online (Sandbox Code Playgroud) typescript ×1