Comment by littlecranky67
7 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
I’m not at my computer so I can’t remember the exact behavior of this situation, but was OP more so referring to autocomplete abilities of typescript? I think they were saying, you first must know if the object barks or meows, you must first type that in in order to get the benefit of type checking and subsequent autocomplete conditional body, which is annoying when you are dealing with complicated types. It requires you to do some hunting in to the types, rather than using a piece of code more like an interface.
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...
4 replies →