首页 > 解决方案 > 为什么 TypeScript 在重新声明变量时不能推断出正确的类型

问题描述

我正在编写一个有点像这样的代码:

function helloWorld(customName: string) {
  return `Hello, ${customName}`;
}

const myName: string | null = null;
const isValidName = myName !== null;

if (isValidName) {
  console.log(helloWorld(myName));
}

如果你在 TypeScript 操场上运行这段代码,你会看到 TypeScript 会抱怨Argument of type 'null' is not assignable to parameter of type 'string'.

不过,情况如何?该代码仅在isValidNameis truthy 时运行,并且isValidName只能在trueif myNameis not时运行null。因此,myName是一个string在这里。为什么这不起作用?

标签: typescript

解决方案


据我了解 - 您将结果存储myName !== null到变量中这一事实会isValidName强制 TypeScript 在运行时检查该值并采取适当的行为(因此调用helloWorld(myName)似乎是非法的,因为isValidName可能是在运行时truefalse在运行时)。

但是,如果您将检查更改为

if (myName !== null) {
  console.log(helloWorld(myName));
}

在这种情况下,TypeScript 将能够检测到唯一可能的类型myName是 a string


推荐阅读