nullthrows
nullthrows copied to clipboard
Add NonNullable to typescript typedef return type
Why
The NonNullable
utility type (https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype) excludes null
and undefined
from a type. While the previous type signature removed null from primitives and simple nullable/undefined-able types, it doesn't remove null from more complex nullable types like conditional types with a nullable branch.
How
- Wrap the return type in
NonNullable
since the returned value is guaranteed not to be null or undefined based on the condition:
if (x != null) {
return x;
}
- Add test showing the use case. Note that without
NonNullable
,nonNullableWrappedDoSomething
doesn't typecheck.
Test Plan
- Temporarily remove
NonNullable
from the returned type. - See that the code no longer typechecks.
- Add
NonNullable
, see it typechecks correctly and matches the test snapshot (the test passes).
friendly ping
friendly ping