by mdtrooper · 8mo ago · 0 comments
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();
}
} 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...
https://www.typescriptlang.org/play/?#code/C4TwDgpgBAIg9gcyg...
I thought the answer was 'instanceof'?
https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...
You can't do `instanceof Dog`. `instanceof` is a JavaScript feature
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Then: isDog(animal) ? animal.bark() : animal.meow() You get full type narrowing inside conditionals using typeguards.
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.
const CatDog = { bark(){}, meow(){} }
and const TreeCat = { bark: "oak", meow(){} }
and your code stops workingTo make types discriminatable you need either
type A = { bark: fn, meow?: never } | { bark?: never, meow: fn }
type B = { species: "dog", bark: fn } | { species: "cat", meow: fn }
or use instanceof with a class