typescript - 为什么 TS 在 console.log(add(b)) 处显示错误?
问题描述
示例代码:
let a: string | undefined;
function echo<T>(a: T): T {
return a;
}
function add(a: string): string {
return `${a}1`;
}
let b = echo(a);
const c = echo(a);
if (!b || !c) {
return;
}
const why = function () {
console.log(add(b)); // Argument of type 'string | undefined' is not assignable to parameter of type 'string'.Type 'undefined' is not assignable to type 'string'
console.log(add(c));
};
为什么const
没有这个错误?b
并且c
基本相同,并且代码确实检查了两个变量天气它们是错误值。我查了一些文档,没有找到解释。
解决方案
因为c
它工作正常,因为这部分:
if (!b || !c) {
return;
}
确保这c
是一个字符串(因为它会在未定义时返回)。此外c
,在此块之后无法更改if
,因为它是一个const
.
另一方面,b
被定义为let
TS 编译器不能确保在if - return
块之后和why
调用函数之前它没有被更改。所以它在任何阶段仍然可以是字符串或未定义。
推荐阅读
- python - 基于文本匹配在 Pandas DataFrame 上加入并运行计算
- jquery - Jquery SetInterval 循环结束再次循环重启
- vb.net - 检索数据库中的数据并显示在日历控件VB.Net-2010 windows窗体应用程序中
- node.js - MongoDB如何访问关系模型和更新
- c - 使用 for 循环向数组输入值
- vim - vim - 在插入/正常时更改行号突出显示
- javascript - 生成“Firebase ID 令牌”(访问令牌)的最简单方法是什么?
- python - 在 Python 的 FoxDot 实时编码环境中使用不同的键
- mongodb - 如何在mongodb中使用`$in`聚合文档?
- authentication - asp.net core - 最简单的身份验证 - 只有两行?