使控制流分析在归纳案例中起作用

如下所示的健全性检查会长时间出现在我的代码中:

if (!someCheck() /* dependent on previously assigned variables */) {
    console.log(someMessage);
    return;
}
someVariables = something; // dependent on someCheck being successful

Here, someCheck typically uses variables set earlier. It somewhat reminds me a bit of "checking deeply nested properties", which nowadays ?. solves.

I wanted to shorten this pattern, so it is less repetitive (don't have to write the if, return, console.log, ..., every time). I've thought of the following scheme:

let varOne = null,
    varTwo = null,
    varThree = null;

let checkAssign = [
    [() => true,                     () => { varOne = { prop: "hello" }; varTwo = ["myData"]; }, "msg1"],
    [() => varOne.prop.length === 5, () => { varThree = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; },      "msg2"],
    [() => varTwo[0] === "myData",   () => { /* no assignments here, can be empty */ },          "msg3"],
]

for (let [check, assign, message] of checkAssign) {
    if (check()) assign();
    else {
        console.log(message);
        return;
    }
}

However, I assume it is too difficult for flow analysis to understand the inductive principle, where pseudo-mathematically speaking, { assign#1, ..., assign#N-1 } --> variables_for_check#N, and that they are only executed in order. Therefore, although it should be clear at compile-time, whether variables will be assigned prior to a check, I'd have to add a runtime check, to assert to the type-checker, that everything is ok (admittedly there may be some not-so-verbose solutions here, maybe i could just not care, if there is a really short one).

有没有一种方法可以让类型检查器在这里了解情况,或者以其他方式表达这种情况,使类型检查器可以理解它,但仍然不像链接成千上万的多行if语句那样冗长?

Additional notes: a functional-oriented approach, where assign#N-1 returns all data for check#N would be another idea. However, to me, it seems equally difficult, to make the type-checker assert, that the list is #N-1 --> #N (very similar issue imho).

评论