理解 !打字稿中的运算符

Understanding ! operator in typescript

我是打字稿的新手,正在努力学习这门语言。

我正在阅读一个组件,我看到了这个:

interface FilterRowProps {
  cannotRemove: boolean
  filterName?: string
}

const field = getField(demo.fields)(filterName!)

问题:

既然filterName props是可选的,那filterName!是什么意思呢?

谁能解释一下?超级糊涂。

!non-null assertion operator。它告诉打字稿“我知道这看起来可能是 null/undefined,但相信我,它不是”。在打字稿无法确定您的代码消除了 null 或 undefined 的可能性的情况下,偶尔需要这样做。

但请注意,与任何类型断言一样,您是在告诉打字稿不要检查您的工作。如果你使用它,它实际上 cannull/undefined,typescript 不会提醒你这个事实,你可能会在运行时出错。

简而言之:您应该很少使用它。大多数时候,如果类型导致打字稿推断它可能是 undefined,那么它可能是正确的。然后您应该编写代码来处理 undefined.