与Flow中TypeScript的非null断言运算符相似吗?

时间:2018-07-25 13:58:59

标签: javascript flowtype

Non-null assertion operator

示例:

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

1 个答案:

答案 0 :(得分:1)

不太相似,但是您可以在let之前添加type casting expression,如下所示:

function processEntity(e?: Entity) {
    validateEntity(e);
    (e: Entity);
    let s = e.name;  // Assert that e is non-null and access name
}

但是如果e为空,则不会让您不感到惊讶,因此我认为使用if是最佳选择:

function processEntity(e?: Entity) {
    validateEntity(e);
    if (e) {
        let s = e!.name;  // Assert that e is non-null and access name
    }
}