| 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();
}
}
|