如何同时检查多个变量是否未定义?

时间:2018-02-21 21:50:57

标签: typescript

给定一些变量列表,我想在运行代码之前检查所有变量是否都未定义。

我的代码下面有4个变量,可能未定义也可能未定义。我可以手动检查a和b,让tsc满意,那些总是数字。

但是我想要一个可以节省输入的解决方案,所以我试图实现一个函数来一次检查几个变量。不幸的是,我无法在不丢失类型信息的情况下使其工作,所以tsc不喜欢这些代码。

我在strictNullChecks上运行此功能。

let a = func1(),
    b = func1(),
    c = func1(),
    d = func1();

function func1() {
  return Math.random() === 0 ? 1 : undefined; 
}

function func2(a: number, b: number) {
  console.log(a);
  console.log(b);
}

function anyUndef(a: any[]): boolean {
  return a.filter(e => typeof e === 'undefined').length > 0;
}

if (typeof a !== 'undefined' && typeof b !== 'undefined') {
  func2(a, b);
}

if (!anyUndef([c, d])) {
  func2(c, d);
}

1 个答案:

答案 0 :(得分:0)

问题是流量控制检查不会考虑在被调用函数内执行的检查。我们可以使用类型保护,但类型保护只能断言单个参数的类型。为了解决这个问题,我们可以使用元组类型:

function allDef<T, T2, T3, T4>(a: [T | undefined, T2 | undefined, T3 | undefined, T4 | undefined]): a is [T, T2, T3, T4] 
function allDef<T, T2, T3>(a: [T | undefined, T2 | undefined, T3 | undefined]): a is [T, T2, T3] 
function allDef<T, T2>(a: [T | undefined, T2 | undefined]): a is [T, T2] 
function allDef<T>(a: [T | undefined]): a is [T] 
function allDef(a: any[]): boolean{
    return a.filter(e => typeof e === 'undefined').length > 0;
}
// Helpers for inferring tuple types
function tuple<T, T2, T3, T4>(a: [T, T2, T3, T4]): typeof a 
function tuple<T, T2, T3>(a: [T, T2, T3]): typeof a 
function tuple<T, T2>(a: [T, T2]): typeof a 
function tuple<T>(a: [T]): typeof a 
function tuple(a: any): typeof a{
    return a;
}

var x = tuple([c, d]); // create the tuple
if (allDef(x)) { // use the type assertion
    [c, d] = x; // restore the values to the variables, they will not be undefined
    func2(c, d);
}

不确定这是否比手动检查更好,但它可以工作,也许更多的变量是有意义的。