简体   繁体   English

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

[英]Typescript is ignoring null or undefined as function return possibility

I have a function where should return a LoginResponse type or null but Typescript lint is ignoring the null possibility and just displaying LoginResponse as possible value.我有一个函数,它应该返回 LoginResponse 类型或 null,但 Typescript lint 忽略了 null 的可能性,只是将 LoginResponse 显示为可能的值。

export const getSession = (): LoginResponse | null => {
  return null
}

在此处输入图片说明

I also tried using undefined without success.我也尝试使用 undefined 没有成功。 Any thoughts?有什么想法吗?

TLDR; TLDR;

tsconfig.json: tsconfig.json:

{
  "compilerOptions": {
    "strict": true
  }
}

command line: tsc --strict命令行: tsc --strict

By default, TypeScript considers null and undefined to be subtypes of all types other types.默认情况下,TypeScript 将nullundefined视为其他类型的所有类型的子类型。 That is to say, everything is nullable and or may not be defined.也就是说,一切都是可以为空的,也可以不定义。

Given two types, Base and Sub where Sub extends Base , their union, Base | Sub给定两种类型, BaseSub ,其中Sub extends Base ,它们的并集Base | Sub Base | Sub , is equivalent to just Base . Base | Sub ,相当于Base Hence, since null is a subtype of all types, it is a subtype of LoginResponse making LoginResponse | null因此,由于null是所有类型的子类型,因此它是LoginResponse的子类型,使得LoginResponse | null LoginResponse | null equivalent to LoginResponse LoginResponse | null相当于LoginResponse

To have TypeScript treat null and undefined as distinct types, unrelated to all others you need to enable --strictNullChecks , a powerful TypeChecking option.要让 TypeScript 将nullundefined视为不同的类型,与所有其他类型无关,您需要启用--strictNullChecks ,这是一个强大的 TypeChecking 选项。

tsconfig.json配置文件

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

Or, on the command line, tsc --strictNullChecks.或者,在命令行上, tsc --strictNullChecks.

The --strictNullChecks option is part of the strict family of powerful typechecking options and we can therefore use --strict , enabling all of them which is highly recommended, not just because it catches more errors and provides more semantics for those errors, but because it improves the quality of type inferences dramatically, making a lot of code that should intuitively work, in fact work. --strictNullChecks选项是强大的类型检查选项的严格系列的一部分,因此我们可以使用--strict ,启用所有强烈推荐的选项,不仅仅是因为它捕获更多错误并为这些错误提供更多语义,而是因为它显着提高了类型推断的质量,使许多应该直观地工作的代码实际上工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM