示例代码:
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
基本上是一样的,代码会检查这两个变量是否为假值。我查了一些文档,没有找到解释。
转载请注明出处:http://www.shenzhenzsmy.com/article/20230515/1980368.html