logoalt Hacker News

mdtrooperyesterday at 11:18 PM8 repliesview on HN

What has always bothered me about TypeScript are union types. If you have a function that receives a parameter such as ‘Dog | Cat’, you cannot separate it. For example:

type Dog = { bark: () => void }

type Cat = { meow: () => void }

function speak(animal: Dog | Cat) {

    if (‘bark’ in animal) {

        animal.bark();

    } else {
        animal.meow();
    }
}

Okay, okay, I know you can filter using ‘in’ to see if it has methods, but in real life, in a company where you have a colleague (who is a golden boy) who writes over-engineered code with hundreds of interfaces of interfaces, you don’t want to spend time searching through the files to find every element that is in the union type.

Whereas in Rust it does:

struct Dog { name: String, }

struct Cat { name: String, }

enum Animal {

    Dog(Dog),

    Cat(Cat),
}

fn process_animal(animal: Animal) {

    match animal {

        Animal::Dog(dog) => {

            println!(‘It is a dog named {}’, dog.name);

        }

        Animal::Cat(cat) => {

            println!(‘It is a cat named {}’, cat.name);

        }
    }
}

I think TypeScript should add a couple of lines of code to the generated JavaScript to do something like:

type Dog = { bark: () => void }

type Cat = { meow: () => void }

function speak(animal: Dog | Cat) {

    if (animal is Dog) {

        animal.bark();

    } else {

        animal.meow();

    }
}

Replies

tshaddoxyesterday at 11:38 PM

The idiomatic way to do this in TypeScript is with discriminated unions. You’re basically just giving the type system an extra property that makes it trivial to infer a type guard (while also making the runtime check in the compiled JavaScript foolproof).

show 1 reply
culitoday at 12:19 AM

Your first code block works exactly as you would expect and has been working like that for many years

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAIg9gcyg...

show 1 reply
littlecranky67today at 12:04 AM

Typeguard is what you are looking for: function isDog(animal: Dog | Cat): animal is Dog { return "bark" in Dog }

Then: isDog(animal) ? animal.bark() : animal.meow() You get full type narrowing inside conditionals using typeguards.

show 1 reply
spankaleetoday at 12:00 AM

You're talking about adding a runtime feature. TypeScript doesn't do that anymore. It can't control what properties are on objects or add new ones - you do that yourself in the standard JavaScript portion of the language. TypeScript only lets you describe what's there.

As a sibling said, discriminated unions are they way to go here. You can also add custom type guard functions if you can't control the objects but you want to centralize the detection of the types, but it's better to let TypeScript do it itself so that you don't mess something up with a cast.

castraltoday at 12:12 AM

You can literally do what your generated example does using a type guard. You can also use method overloaded signatures if you dont want to expose your API consumers to union types.

epolanskitoday at 12:00 AM

You need a tagged union for this in typescript.

paulddrapertoday at 12:29 AM

You're looking for a discriminated union [1], which idiomatically:

  type Dog = { bark(): void; type: 'dog' }

  type Cat = { meow(): void; type: 'cat' }

  function speak(animal: Dog | Cat) {
    if (animal.type === 'dog') {
      animal.bark()
    } else {
      animal.meow()
    }
  }
Generally speaking, TypeScript does not add runtime features.

TypeScript checks your use of JavaScript runtime features.

[1] https://www.convex.dev/typescript/advanced/type-operators-ma...

zemyesterday at 11:49 PM

this post on union types versus sum types is worth a read (the tl;dr is that they both have their uses and one is not strictly better) https://viralinstruction.com/posts/uniontypes/