Hacker News new | ask | show | jobs
by parhamn 1544 days ago
> In fact, I would say that flow typing is almost like a workaround for missing pattern matching.

If flow typing is 'type narrowing' (the article kinda dragged on pulling in unrelated concepts so it lost me), then if anything, it is at least as good as pattern-matching/switch-blocks. At least in Typescript. That is because it works in switch statements and non-switch statements and provides the same guarantees. I don't get this argument.

Consider something like:

    data: {pages: number} | null = f()
    if (!data){
       return 0
    }
    return data.pages + 5

Sure you can switch on the 'data' as well (exhaustive type-switches are a thing in Typescript too), but thats a syntactic preference. It surely is nice to get the same guarantees without _needing_ a switch statement.
2 comments

> I don't get this argument.

Maybe it's because you focus on typescript here. But typescript is in a position that other languages are not: it has to make things work within an existing ecosystem, in particular with an untyped language. Under these constraints, flow typing might be the best solution. But that doesn't mean it's generally "at least as good as pattern-matching/switch-blocks".

Btw, pattern matching and switch-blocks are very different things - maybe it make it easier for you to understand to dive into a language that has native pattern matching and no switch-blocks at all because from what you write it seems to me that you have not been exposed to pattern matching much yet.

> It surely is nice to get the same guarantees without _needing_ a switch statement.

Is it?

    let data: Some(usize) = f();
    match data {
        Some(pages) => pages + 5,
        None => 0
    }
Seems pretty nice.

Or if you want a more structurally similar code with a guard (and removing the useless bits):

    let Some(pages) = f() else {
        return 0
    };
    pages + 5
> Seems pretty nice.

Never said it's not. I'm just saying it's nice to have type narrowing everywhere since it includes block based switching/matching as well (what you're arguging is nice, which I'd agree)

You'll have to use your imagination here because in typescript narrowing works on all conditionals (ternaries, boolean switches, etc), so naturally there are many more examples where it's useful. It's easy to trivialize any specific example.

E.g. they're useful in JSX when you want to do a one-line type-safe boolean switches like: {node && <RenderNode node={node}/>}.