小编Zbi*_*ski的帖子

打字稿类似断言的类型保护

这是可能有不限制类型if的函数调用never回报例如undefinedassert在打字稿?

示例代码:

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

6
推荐指数
2
解决办法
1921
查看次数

标签 统计

typescript ×1