Hacker News new | ask | show | jobs
by paavohtl 1863 days ago
In TypeScript perhaps the most important use case for literal types is the ability to to create discriminated unions, or algebraic datatypes (ADTs). Many modern languages have a separate feature for this (such as enums in Rust), but in TypeScript they can be constructed using literal and union types. Here's an example:

    interface ProductOffer { 
        kind: 'productOffer'
        eans: Ean[]
        discountPercentage: number
    }

    interface GroupOffer {
        kind: 'groupOffer'
        groups: GroupId[]
        discountPercentage: number
    }

    type Offer = ProductOffer | GroupOffer

Also check the TypeScript handbook for more information: https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...
1 comments

I think it is important to emphasize that there is actually an important difference.

Union types don't allow to model GADTs, so they are less powerful than what some other languages offer. But on the other side, they allow for much easier composition. E.g.:

type Citrus = "Orange" | "Lemon" type Prunus = "Plum" | "Apricot"

Now in typescript you can just do:

type Fruit = Citrus | Prunus

But in many other languages it's not so easy and you have to jump through hoops and e.g. either redefine the types and/or refactor the code (if you can even do that - if the code is from 3rd party libraries you are out of luck).