Comment by littlecranky67
5 hours ago
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.
You don't even need that. The code exactly as presented acts as a discriminator. TypeScript is smart enough to handle that logic in the if block and know whether animal has been validated as Dog vs Cat. GP is complaining about a feature that already exists in TypeScript
It depends how you construct Dog and Cat. With Javascripts dynamic prototype chain, you could never know for sure.
Try it
https://www.typescriptlang.org/play/?#code/C4TwDgpgBAIg9gcyg...
3 replies →