nullthrows icon indicating copy to clipboard operation
nullthrows copied to clipboard

Add NonNullable to typescript typedef return type

Open wschurman opened this issue 4 years ago • 2 comments

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

  1. 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;
}
  1. Add test showing the use case. Note that without NonNullable, nonNullableWrappedDoSomething doesn't typecheck.

Test Plan

  1. Temporarily remove NonNullable from the returned type.
  2. See that the code no longer typechecks.
  3. Add NonNullable, see it typechecks correctly and matches the test snapshot (the test passes).

wschurman avatar Nov 24 '20 18:11 wschurman

friendly ping

wschurman avatar May 03 '21 18:05 wschurman

friendly ping

wschurman avatar Mar 07 '23 20:03 wschurman