首页 > 解决方案 > 为什么 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基本相同,并且代码确实检查了两个变量天气它们是错误值。我查了一些文档,没有找到解释。

标签: typescript

解决方案


因为c它工作正常,因为这部分:

if (!b || !c) {
    return;
}

确保这c是一个字符串(因为它会在未定义时返回)。此外c,在此块之后无法更改if,因为它是一个const.

另一方面,b被定义为letTS 编译器不能确保在if - return块之后和why调用函数之前它没有被更改。所以它在任何阶段仍然可以是字符串或未定义。


推荐阅读