Encountered a peculiar situation while working on a project. Take a look at this example where TS flags an error:
type Fruit = {
name: string;
};
const myFruits: Fruit[] = [{ name: "Apple" }, { name: "Banana" }];
let asyncFuncResult: string | undefined = "NewName";
const asyncFuncResultConst: string | undefined = "NewName";
let result;
// Why is TS raising an issue here?
if (asyncFuncResult) {
result = myFruits.map(
(fruit): Fruit => {
return {
...fruit,
name: asyncFuncResult
};
}
);
}
It reports on line name: asyncFuncResult
saying:
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'
https://i.sstatic.net/uoEfv.png
Here is the demo and possible solutions I found to resolve it: CodeSandBox Demo
But what confuses me is why the error occurs. We don't enter the condition block if the variable is undefined. Therefore, there should be no scenario where we assign an undefined value to a string.