Typescript is ignoring null or undefined as function return possibility

Viewed 1111

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.

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

enter image description here

I also tried using undefined without success. Any thoughts?

1 Answers

TLDR;

tsconfig.json:

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

command line: tsc --strict

To understand why this behavior is expected we need to consider two facts:

  1. When --strictNullChecks is disabled (the default), TypeScript considers null and undefined to be subtypes of all types other types. That is to say, everything is nullable and may not be defined. This means that for any type T, Tis equivalent to T | null | undefined. Contrariwise, when --strictNullChecks it is enabled, Tis distinct from T | null | undefined.

  2. Given two types, Base and Sub where Sub extends Base, their union, Base | Sub, is equivalent to just Base. Hence, since null is a subtype of all types, it is a subtype of LoginResponse making LoginResponse | null equivalent to LoginResponse

To have TypeScript treat null and undefined as distinct types, unrelated to all others you need to enable --strictNullChecks, a powerful TypeChecking option.

tsconfig.json

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

Or, on the command line, 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.

Related