1

Here's an example of a TypeScript type:

type NonNullable<T> = T extends null ? never : T 


type Test1 = NonNullable<string>; // string
type Test2 = NonNullable<string | null>; // still string!

The ternary operator is applied individually to each member of the T union. Now, I'd like to create a type that looks at union T as a whole, like this:

type NonNullable2<T> = ...?


type Test1 = NonNullable<string>; // string
type Test2 = NonNullable<string | null>; // never, because the provided T (string|null) extends null.

So, if I provide any T that can be null, I want to get never. Any other type should return T. How can I do that?

mnj
  • 2,539
  • 3
  • 29
  • 58
  • 1
    Tangential: [Since TS version `4.8`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-8.html#improved-intersection-reduction-union-compatibility-and-narrowing), the `NonNullable` utility type is now written as `type NonNullable = T & {};`. – jsejcksn Nov 24 '22 at 11:19
  • I agree that the linked question answers mine. However, I wasn’t able to find it, because I did not know that the thing I encountered has a name - Distributive Conditional Types. An information about that and a link to TS docs would be the right answer to my question – mnj Nov 28 '22 at 17:15
  • [^](https://stackoverflow.com/questions/74559534/ternary-expression-in-type-that-looks-at-a-union-as-a-whole?noredirect=1#comment131686702_74559534) @mnj Your question is still a duplicate, and now it exists and is searchable for others — and includes a link to the other question so that they can read the answer and learn the name also. – jsejcksn Nov 28 '22 at 17:20

0 Answers0