typescript “?”和“?”有什么区别|未定义”?

cld4siwp  于 6个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(87)

我想知道,是否有区别(实际或最佳做法明智的)之间

interface Fruit {
  cost?: number;
}

字符串

interface Fruit {
  cost: number | undefined;
}


如果在行为方面有实际的差异,那是什么?
如果没有,为什么人们会喜欢| undefined?:(反之亦然)?
有点困惑,因为我都看过了,不确定是否真的有一个实际的原因,更喜欢一个比另一个,或者如果它只是归结为偏好的东西。
谢谢你,谢谢

ekqde3dh

ekqde3dh1#

一个区别是cost: number | undefined; * 要求 * 属性存在,并且具有类型为numberundefined的值。相反,cost?: number允许属性根本不存在。
编译失败:

interface Fruit {
    cost: number | undefined;
}
const x: Fruit = {};

字符串
为了让它工作,你必须做:

interface Fruit {
    cost: number | undefined;
}
const x: Fruit = { cost: undefined };


但这成功了:

interface Fruit {
    cost?: number;
}
const x: Fruit = {};


如果有其他选择,则显式输入undefined可能会很繁琐,因此您可能更喜欢cost?: number选项。

相关问题