DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
kspeakman profile image
Kasey Speakman

Typescript union types are a bit different from those in F#. There is a tradeoff made between them. Union declarations are more or less anonymous in Typescript, whereas F# requires you to create a Discriminated Union with explicit tags. So, the Typescript feels a little nicer on declaration. However, when you unpack the union type, I believe F# has the advantage. Using match you can get auto-completion of the cases and warning when all cases are not exhaustively matched. It also provides access to the value as the appropriate type.

Examples:

// TypeScript
function padLeft(value: string, padding: string | number) {
    if (typeof padding === "number") {
        return Array(padding + 1).join(" ") + value;
    }
    if (typeof padding === "string") {
        return padding + value;
    }
}

// usage
let foo = padLeft("padded", 4);
// "    padded"
let bar = padLeft("padded", "bar ");
// "bar padded"
Enter fullscreen mode Exit fullscreen mode
// F#
type Padding =
    | Text of string
    | Spaces of int

let padLeft padding str =
    match padding with
    | Text prefix ->
        prefix + str
    | Spaces count ->
        String.replicate count " " + str

// usage
let foo = padLeft (Spaces 4) "padded"
// "    padded"
let bar = padLeft (Text "bar ") "padded"
// "bar padded"
Enter fullscreen mode Exit fullscreen mode

So, I feel like the latter is a better expression of intent in the long run. Even though it requires an extra type declaration, the type declaration adds some value for readability. It is more clear what the code is going to do with "string | number" when labeled as Text and Spaces.

For F#, I also swapped the order of arguments so that padLeft would be chainable with other string functions using pipe (|>).

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha

What a wonderful response. Thank you for being generous with your time to write that thoughtful response. You should post that as it’s own article so more people can benefit from it. :)