首页 > 解决方案 > 使用布尔常量检查参数是否定义

问题描述

使用 Typescript 2.8.3,我不明白为什么以下代码无法获取在 if 块中定义的参数。

const testFunction = (params?: string) => {
  const paramIsDefined = typeof params !== 'undefined';
  if (paramIsDefined) {
    console.log(params.length);
  }
};

我收到此错误:TS2532: Object is possible 'undefined' on the console.log line for the params 变量。

而这段代码有效:

const testFunction = (params?: string) => {
  if (typeof params !== 'undefined') {
    console.log(params.length);
  }
};

我不理解/做错了什么?

标签: typescript

解决方案


构造:

if (typeof params !== 'undefined') {
    console.log(params.length);
}

是类型保护,因此会影响params.

if (paramIsDefined)只是一个if声明,检查的布尔值确实来自类型检查,但编译器根本不遵循这一点。如果您想将params表单类型缩小string|undefined到只string需要使用类型保护构造或使用断言


推荐阅读