Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 类型脚本类型推断不适用于函数类型保护_Typescript - Fatal编程技术网

Typescript 类型脚本类型推断不适用于函数类型保护

Typescript 类型脚本类型推断不适用于函数类型保护,typescript,Typescript,在alpha中,我检查结果是否为null,如果是,则抛出新错误,但comiler仍显示编译错误: const obj = { objMethod: function (): string | null { return 'always a string'; }, }; function alpha() { if (obj.objMethod() === null) { throw new Error('type guard, but compiler does n

alpha
中,我检查结果是否为
null
,如果是,则
抛出新错误
,但comiler仍显示编译错误:

 const obj = {
  objMethod: function (): string | null {
    return 'always a string';
  },
};

function alpha() {
  if (obj.objMethod() === null) {
    throw new Error('type guard, but compiler does not count it as one :( ');
  }

  const beta: string = obj.objMethod();
  console.log(beta);
}
但这段代码运行得非常好:

const obj = {
  objMethod: function (): string | null {
    return 'always a string';
  },
};

function alpha() {
  const result = obj.objMethod();
  if (result === null) {
    throw new Error('this DOES count as a type guard. ');
  }

  const beta: string = result; // no error
  console.log(beta);
}

Typescript无法证明您的
objMethod
总是返回相同的值。它可以在第一次调用时返回非null值,在第二次调用时返回null值。如果将其分配给常量变量,则该检查将断言该变量不为null。由于变量为常量,赋值后该值不能更改,因此,如果通过检查,则该值必须为非null