typescript - 为什么 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'.
不过,情况如何?该代码仅在isValidName
is truthy 时运行,并且isValidName
只能在true
if myName
is not时运行null
。因此,myName
是一个string
在这里。为什么这不起作用?
解决方案
据我了解 - 您将结果存储myName !== null
到变量中这一事实会isValidName
强制 TypeScript 在运行时检查该值并采取适当的行为(因此调用helloWorld(myName)
似乎是非法的,因为isValidName
可能是在运行时true
或false
在运行时)。
但是,如果您将检查更改为
if (myName !== null) {
console.log(helloWorld(myName));
}
在这种情况下,TypeScript 将能够检测到唯一可能的类型myName
是 a string
。
推荐阅读
- php - PHP中的动态类使用
- jboss - Jboss Fuse ESB 6.3 上的 Appdynamics Instrumentation
- model - 在 gensim 包装器中访问模型
- php - 在 CodeIgniter 中通过 jQuery AJAX 插入和移动多个图像
- ios - 在 iOS SDK 的 App Modules 中添加框架
- php - 如何使用 PHP 在我所有来自 mysql 的帖子中获得最受欢迎的帖子
- arrays - swift中连续数组的数据结构
- azure - 如何查找流的订阅 ID 和资源组名称
- html - iPhone VoiceOver 不发音箭头的文本
- python - 通过 Selenium 选择下拉选项