Hacker News new | past | comments | ask | show | jobs | submit login

in F#, yes, in TypeScript, not really. The technique involves using a combo of an opaque nominal type, and a smart constructor:

    (* GreaterThanTwo.fsi *)

    type t

    val make : int -> t option
    val to_int : t -> int

    (* GreaterThanTwo.fs *)

    type t = Value of int

    let make int = if int > 2 then Some (Value int) else None
    let to_int (Value int) = int
Now, `GreaterThanTwo.make x` gives you a value of type `GreaterThanTwo.t option`, meaning it can be `Some` value or `None`. If it's `Some` value, that means it really does contain an int greater than two and you can get that int using `GreaterThanTwo.to_int`.



Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: