Javascript 检查函数是否始终返回布尔值

Javascript 检查函数是否始终返回布尔值,javascript,predicate,Javascript,Predicate,我需要检查用户指定的谓词是否总是返回布尔值。示例代码如下所示: let isMostlyBoolean = function (aPredicate) { return ( typeof aPredicate(undefined) === 'boolean' && typeof aPredicate(null) === 'boolean' && typeof aPredicate(false) === 'boolean' &&

我需要检查用户指定的谓词是否总是返回布尔值。示例代码如下所示:

let isMostlyBoolean = function (aPredicate) {

return ( typeof aPredicate(undefined) === 'boolean' &&
    typeof aPredicate(null) === 'boolean' &&
    typeof aPredicate(false) === 'boolean' &&
    typeof aPredicate(Number.NaN) === 'boolean' &&
    typeof aPredicate(256) === 'boolean' &&
    typeof aPredicate("text") === 'boolean' &&
    typeof aPredicate('s') === 'boolean' &&
    typeof aPredicate(Math.sqrt) === 'boolean' &&
    typeof aPredicate(Object) === 'boolean' &&
    typeof aPredicate(['x', 'y', 'z']) === 'boolean'
);

}
这很有效。是否有更整洁和/或有效的方法进行定期检查?在这里,我们逐一扫描所有可能的内容

正如讨论中所述,
类型的
应该是正确的选择。你知道如何以更奇特、更易读的方式做到这一点吗

编辑:注意上面的测试是一种模糊逻辑。函数名已相应更改。请参阅下面的@georg评论和更多内容

给定测试代码:

let prediLess = (x) => x<2;
let predicate = (x) => x || (x<2);

console.log("isMostlyBoolean(prediLess): ", isMostlyBoolean(prediLess));
console.log("isMostlyBoolean(predicate): ", isMostlyBoolean(predicate));

console.log("\nprediLess(undefined): ", prediLess(undefined));
console.log("prediLess(1): ", prediLess(1));
console.log("prediLess(Object): ", prediLess(Object));

console.log("\npredicate(undefined): ", predicate(undefined));
console.log("predicate(1): ", predicate(1));
console.log("predicate(Object): ", predicate(Object));

只需将所有可能的值存储在一个数组中并对其进行迭代,然后检查每个值是否合适。

我不确定您的函数应该检查什么。Javascript是松散类型的,不能保证给定类型A的参数,函数总是返回类型B。因此,
aPredicate
完全可能返回
boolean
表示“256”,返回一个数字表示“257”…同意。如果你想要typesafety,你应该看看typescript…@georg它是为了提高效率。给定一个函数,如
newGenerator(oldGenerator,aPredicate)
aPredicate
配置错误,我们不调用
oldGenerator
,新函数只返回
未定义的
returnsBoolean(prediLess):  true
returnsBoolean(predicate):  false

prediLess(undefined):  false
prediLess(1):  true
prediLess(Object):  false

predicate(undefined):  false
predicate(1):  1
predicate(Object):  function Object() { [native code] }
 [undefined, null, NaN, 0, 1, "", "a", [], [1], {}].every(el => typeof aPredicate(el) === "boolean");