为什么 TypeScript 接受不使用“?”运算符如果对象是可选的?

Why TypeScript accept not to use "?" operator if object is an optional?

这里我们有这个方法:

export const showGiftedOrGiftingEmail = (
  transaction: Transaction
): { [a: string]: string } | null => {

显然 return 一个可选的,可以是一个对象或 null。但是这里它接受没有 ? 运算符的表达式,为什么?

showGiftedOrGiftingEmail(props.transaction).email

?

showGiftedOrGiftingEmail(props.transaction)?.email

如果不强制这种类型安全,使用 Typescript 有什么意义? Swift 永远不会接受第一个表达式。

What is the point of use Typescript if it does not force out this kind of type safety? Swift would never accept the first expression.

默认情况下,TypeScript 也不接受第一个示例。你可以看到它是如何报错的 here

如果您关闭 strictNullChecks,它将停止给出该错误。这是预期的行为。将现有 JS 代码库迁移到 TS 时,标志 can 的一种可能用途。

Why web has the null and the undefined expression? It seems overkill.

null 用于您知道设置为空的值(如您的示例)。 undefined 是它们在声明但未设置值时获得的默认值。当您想检查某些内容是否有意或默认设置为空时,这实际上很有用。