Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conditional typing in Flow #37

Open
sibelius opened this issue Jun 7, 2018 · 1 comment
Labels

Comments

@sibelius
Copy link

@sibelius sibelius commented Jun 7, 2018

https://github.com/niieani/typescript-vs-flowtype#conditional-typing

You can the same, check this helper: https://gist.github.com/miyaokamarina/934887ac2aff863b9c73283acfb71cf0

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,
>;

////

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);

////

declare var e: $If<$Gte<number, string>, 1, 2>;

/* error  5 */ (e: 1);
/* ok       */ (e: 2);

declare var f: $If<$Gte<number, number>, 1, 2>;

/* ok       */ (f: 1);
/* error  6 */ (f: 2);

////

type IsNumber<X> = $Gte<number, X>;

type NumberTo12<X> = $If<IsNumber<X>, 1, 2>;

declare var g: NumberTo12<string>;

/* error  7 */ (g: 1);
/* ok       */ (g: 2);

declare var h: NumberTo12<number>;

/* ok       */ (h: 1);
/* error  8 */ (h: 2);
@niieani

This comment has been minimized.

Copy link
Owner

@niieani niieani commented Jun 7, 2018

Cool stuff! Can you make a PR?

@niieani niieani added the help wanted label Oct 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.