在一个项目上陷入了一个奇怪的境地.以下是TS显示错误的示例:
type Fruit = {
name: string;
};
const myFruits: Fruit[] = [{ name: "Apple" }, { name: "Banana" }];
let asyncFuncResult: string | undefined = "NewName";
const asyncFuncResultConst: string | undefined = "NewName";
let result;
// Why TS shows an issue here?
if (asyncFuncResult) {
result = myFruits.map(
(fruit): Fruit => {
return {
...fruit,
name: asyncFuncResult
};
}
);
}
它对第name: asyncFuncResult
行说:
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'
以下是我找到的解决方法的演示和方法: CodeSandBox Demo个
但我不明白为什么它会显示错误.如果变量是未定义的,我们不会进入条件块.因此,我们不可能将未定义的值赋给字符串.