javascript - 使用闭包编译器创建结果类型

标签 javascript error-handling google-closure-compiler

我正在使用 Closure Compiler,并且希望有一个类似 Rust 的 Result 类型,它要么包含特定类型的值,要么不包含任何值和错误,以表示从函数返回值。

以下是我的意思的示例:

/**
 * @param {function(Result<Element>)} callback
*/
function bar (callback) {        
    if (...) {
        var elem = ...;
        callback(Result.ok(elem));
    } else {
        callback(Result.err(new Error("...")));
    }
}

bar(function (result) {
    if (result.ok) {
        // guaranteed to be a non-error result here - no warning
        console.log(result.val.nodeType);
    } else {
        // closure should produce a warning here about undefined prop
        console.log(result.val.nodeType);
    }
});

可能的实现(但不会抛出警告):

/**
 * @constructor
 * @template T
 * @param {boolean} ok
 * @param {T} val
 * @param {Error} err
**/
function Result (ok, val, err) {
    this.ok = ok;
    this.val = val;
    this.err = err;
}

/**
 * @template T
 * @param {T=} val
 * @return {OkResult<T>}
**/
Result.ok = function (val) {
    return new OkResult(val);
};

/**
 * @param {Error} err
 * @param {Error=} previous
 * @return {ErrResult}
**/
Result.err = function (err, previous) {
    err['previous'] = previous;
    return new ErrResult(err);
};

/**
 * @constructor
 * @extends {Result}
 * @template T
 * @param {T} val
**/
function OkResult (val) {
    this.ok = true;  
    this.val = val;
    this.err = null;
}

/**
 * @constructor
 * @extends {Result}
 * @param {Error} err
**/
function ErrResult (err) {
    this.ok = false;
    this.val = null;
    this.err = err;
}

我尝试使用 Result 父类(super class)和两个 OkResultErrResult 子类来实现此功能,但是当我尝试编写代码时应该会产生警告,但我没有收到任何警告。

是否有某种方法可以创建具有上述指定属性的 Result 类型?当尝试访问错误结果时会像正常结果一样安全地发出警告?

最佳答案

使用经典继承绝对是做到这一点的方法。检查应该是 instanceof,而不是测试 obj.ok 属性。

bar(function (result) {
  if (result instanceof OkResult) {
    // instanceof tests are recognized by the compiler
    // and automatically tightens the types.
    console.log(result.val.nodeType);
  } else if (result instanceof ErrorResult) {
    // closure produces a warning here about undefined prop
    console.log(result.val.nodeType);
  }
});

此外,编译器仅在属性不存在时才警告缺少属性。为了实现这一点,不得在任何父类上定义该属性。

See a working example

关于javascript - 使用闭包编译器创建结果类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34277508/

相关文章:

javascript - jQuery 用另一个替换给定的链接

asp.net-mvc - AJAX错误处理

facebook - 您如何以编程方式判断图形 API 错误是哪种错误?

Haskell:约束中的非类型变量参数?

google-closure-compiler - Google Closure Builder - 防止 base.js 插入

javascript - 闭包编译器没有使用 && 将此 if 语句扁平化为 "guard"

templates - Dojo 构建请求已内联的模板

javascript - BS 3 在单击链接并显示选项卡时获取数据属性值

php - 如何使用谷歌访问 token 获取用户电子邮件?

javascript - 使用 javascript 优雅地修改现有链接的参数