Non-null and non-undefined type in Flow

2.6k views Asked by At

Flow defines so called "Maybe types". I.e. ?string is similar to string | null | void (void is a type of value undefined).

Is there something like general type that can be of any value but null and undefined? Basically something like $Diff<$Diff<any, null>, void> if $Diff operator was able to operate on non-object types.

3

There are 3 answers

0
vkurchatkin On BEST ANSWER

There is no some "magic" type for this, but something like this should work: string | number | boolean | {} | []

0
thomazmz On

If you need only a "shallow" type that does not allow null or undefined:

export type NotNullOrUndefined = 
   | string
   | number 
   | bigint
   | []
   | {}

Now, in case you want to propagate the not null and not undefined requirement in values nested under objects and arrays you will need the following:

export type NotNullOrUndefined = 
   | string
   | number 
   | bigint
   | NotNullOrUndefined[]
   | { [k: string]: NotNullOrUndefined }
3
JBE On

It is possible using the NonMaybeType Flow utility type: see $NonMaybeType

$NonMaybeType<T> converts a type T to a non-maybe type. In other words, the values of $NonMaybeType<T> are the values of T except for null and undefined.

// @flow
type MaybeName = ?string;
type Name = $NonMaybeType<MaybeName>;

('Gabriel': MaybeName); // Ok
(null: MaybeName); // Ok
('Gabriel': Name); // Ok
(null: Name); // Error! null can't be annotated as Name because Name is not a maybe type