TS check if Type contains 'null' Type

388 Views Asked by At

I have the following both Typescript Types defined. One of the type contains nullthe other neither. Is it possible to check such type for the existence of null?

type TransactionCategory = "B2B"| "SEZWP" | "SEZWOP" | "EXPWP" | "EXPWOP" | "DEXP" | null

type DutyStatus = "WPOD" | "WOPOD" 

I don't want to check such stuff on the concrete instance but on the type system itself. Similar to the in keyword.

1

There are 1 best solutions below

0
jsejcksn On BEST ANSWER

It's not exactly clear what you're asking, but...

If you just want to get a boolean verdict from the compiler about whether the type null is included in a union type, then you can write a simple generic utility type to check that:

TS Playground

type TransactionCategory = "B2B"| "SEZWP" | "SEZWOP" | "EXPWP" | "EXPWOP" | "DEXP" | null;
type DutyStatus = "WPOD" | "WOPOD";

type IncludesNull<T> = null extends T ? true : false;

type TransactionCategoryIncludesNull = IncludesNull<TransactionCategory>;
   //^? type TransactionCategoryIncludesNull = true

type DutyStatusIncludesNull = IncludesNull<DutyStatus>;
   //^? type DutyStatusIncludesNull = false