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
}

I also tried using undefined without success. Any thoughts?
TLDR:
In tsconfig.json:
{
"compilerOptions": {
"strict": true
}
}
Via command line:
tsc --strict
To understand why the behavior outlined in your question is indeed expected we need to consider two facts:
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 undefinable. This means that for any type T, T is equivalent to T | null | undefined.
Contrariwise, when --strictNullChecks it is enabled, T is distinct from T | null | undefined for all types save any.
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 powerful strict family of checks wherefore we can use the --strict option, enabling all of them. This is 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 inference dramatically, making a lot of code that should intuitively work, in fact work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With