This page looks best with JavaScript enabled

Quick Tips - variadic unions in typescript

 ·  ☕ 1 min read

    A lot of the time, you want to define union types in typescript, and you would set it up like this by default for a small collection of enumerated values-as-types:

    1
    
    type Foobar = "foo" | "bar" | "baz";
    

    A better way to scale this with more value options, is to use an array index as a type, and have that array contain your options:

    1
    2
    3
    4
    5
    6
    
    const FoobarOptions = [
    	"foo",
    	"bar",
    	"baz"
    ] as const;
    type Foobar = typeof FoobarOptions[number];
    

    This would do the same thing but it is way less annoying to deal with when you end up with a lot of options.

    Share on

    abschill
    WRITTEN BY
    abschill
    software engineer