DEV Community

Ryan Frazier
Ryan Frazier

Posted on • Originally published at pianomanfrazier.com on

Case Statement in Typescript

One of my favorite features of functional languages like Elm is pattern matching. Here is an example:

type State
    = Loading
    | Error
    | Ok

stateToString : State -> String
stateToString state =
    case state of
        Loading ->
            "Loading ..."
        Error ->
            "Something went wrong."
        Ok ->
            "It's all good"
Enter fullscreen mode Exit fullscreen mode

I found a simple way to provide an action for every case of a TypeScript enum.

enum State {
    Loading,
    Error,
    Ok,
}

const STATE_MAP = {
    [State.Loading] : () => "Loading ...",
    [State.Error] : () => "Something went wrong.",
    [State.Ok] : () => "It's all good",
}

function stateToString(state : State) : string {
    return STATE_MAP[state]();
}
Enter fullscreen mode Exit fullscreen mode

Link to TypeScript playground

Usually TypeScript won't allow bracket notation to access properties of an object. In this case the compiler knows that all cases of State are accounted for and can thus be used to index into the object.

Try removing one of the states from STATE_MAP and the TypeScript compiler will yell at you.

Element implicitly has an 'any' type because expression of type 'State' can't be used to index type '{ 0: () => string; 1: () => string; }'.
Property '[State.Ok]' does not exist on type '{ 0: () => string; 1: () => string; }'.
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (2)

Collapse
 
rspsuresh profile image
suresh rampaul

Nice one. Keep it up

Collapse
 
pianomanfrazier profile image
Ryan Frazier

Thanks.

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay