打字稿忽略 null 或 undefined 作为函数返回的可能性

Bru*_*sma 2 typescript

我有一个函数,它应该返回 LoginResponse 类型或 null,但 Typescript lint 忽略了 null 的可能性,只是将 LoginResponse 显示为可能的值。

export const getSession = (): LoginResponse | null => {
  return null
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我也尝试使用 undefined 没有成功。有什么想法吗?

Alu*_*dad 5

TLDR;

tsconfig.json:

{
  "compilerOptions": {
    "strict": true
  }
}
Run Code Online (Sandbox Code Playgroud)

命令行: tsc --strict

默认情况下,打字稿认为nullundefined为所有类型的其他类型的亚型。也就是说,一切都是可以为空的,也可以不定义。

给定两种类型,Base并且Subwhere Sub extends Base,它们的并集 ,Base | Sub等价于 just Base。因此,由于null是所有类型的子类型,因此它是LoginResponse使LoginResponse | null等价于的子类型LoginResponse

要让 TypeScript 将nullundefined视为不同的类型,与您需要启用的所有其他类型无关,这--strictNullChecks是一个强大的 TypeChecking 选项。

配置文件

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,在命令行上, tsc --strictNullChecks.

--strictNullChecks选项是强大的类型检查选项的严格系列的一部分,因此我们可以使用--strict,启用所有强烈推荐的选项,不仅因为它捕获更多错误并为这些错误提供更多语义,还因为它提高了类型的质量推理显着,使许多应该直观地工作的代码实际上工作。