4

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.

czerny
  • 15,090
  • 14
  • 68
  • 96

3 Answers3

5

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

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
3

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
JBE
  • 11,917
  • 7
  • 49
  • 51
  • So how is type definition of `any` except for `undefined` and `null` expressed using `$NonMaybeType` going to look like? I've [tried](https://flow.org/try/#0PTAEAEDMBsHsHcBQ0CmAXUAPAXKAJAHKwB2AsgIYCeARigCqUAOKAPOcZQHyKagC8oYgFdo0Hv1BDiAExSQAlsRTTEiIA) `$NonMaybeType` and it doesn't seem to work as expected - it allows both `null` and `undefined`. – czerny Oct 23 '18 at 01:48
  • Correct, it does not work for `any`. I did not find a workaround for it. If your function takes as an argument any types however it's possible to express the fact that it will return a non maybe type: `function test(a: A): $NonMaybeType { /*... */ }` (that was my use case) – JBE Oct 23 '18 at 18:58
  • "So how is type definition of any except for undefined and null expressed using $NonMaybeType" - The answer is: `$NonMaybeType` – bvaughn Feb 05 '20 at 19:20
0

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 }
thomazmz
  • 91
  • 2
  • 7