Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional types in flow

Is it possible to type a variable in flow based on a condition? Something like this:

const type = 'xyz';
const a: (type === 'xyz') ? number : string;
like image 783
Kiechlus Avatar asked Jun 29 '17 11:06

Kiechlus


1 Answers

Type-level conditions in Flow may be simulated using type calls ($Call type):

type $If<X: boolean, Then, Else = empty> = $Call<
    & ((true, Then, Else) => Then)
    & ((false, Then, Else) => Else),
    X,
    Then,
    Else,
>;

type $Not<X: boolean> = $If<X, false, true>;
type $And<X: boolean, Y: boolean> = $If<X, Y, false>;
type $Or<X: boolean, Y: boolean> = $If<X, true, Y>;

type $Gte<X, Y> = $Call<
    & ($Subtype<X> => true)
    & (mixed => false),
    Y,
>;

// Usage example:

declare var a: $Gte<number, string>;

/* error  1 */ (a: true);
/* ok       */ (a: false);

declare var b: $Gte<number, number>;

/* ok       */ (b: true);
/* error  2 */ (b: false);

declare var c: $If<true, 1, 2>;

/* ok       */ (c: 1);
/* error  3 */ (c: 2);

declare var d: $If<false, 1, 2>;

/* error  4 */ (d: 1);
/* ok       */ (d: 2);

More usage examples may be found in gist.

like image 78
Marina Miyaoka Avatar answered Oct 20 '22 14:10

Marina Miyaoka