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;
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With