我正在使用 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)和两个 OkResult
和 ErrResult
子类来实现此功能,但是当我尝试编写代码时应该会产生警告,但我没有收到任何警告。
是否有某种方法可以创建具有上述指定属性的 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);
}
});
此外,编译器仅在属性不存在时才警告缺少属性。为了实现这一点,不得在任何父类上定义该属性。
关于javascript - 使用闭包编译器创建结果类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34277508/