在一个项目中遇到了奇怪的情况。这是 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 演示
但我不明白为什么它显示错误。如果变量未定义,我们不会进入条件块。所以我们无法将未定义的值分配给字符串。
Typescript 使用静态类型。在运行时、if 语句运行之前,会检查变量的类型。
type Fruit = {
name: string;
};
在提供的代码中,Fruit中的name的数据类型显式设置为string。因此,map 函数期望返回值的名称为 string 类型,而不是 undefined。尝试分配一个“未定义”值而不在代码中明确指出将导致错误。 如果您希望分配一个
undefined 值,您应该在代码中明确执行此操作,如下所示:
type Fruit = {
name: string | undefined;
};
您还可以通过简单地在代码中使用非空断言
运算符来抑制警告,如下所示。
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! // Add a non-null assertion operator
};
}
);
}