I find your example of Typeguard a little problematic precisely because it is subject to fail in the case of "interface growth". Determining type based on the presence of a method looks really flaky to me. As already suggested a duck would be identified as a fish. In your example code it makes much more sense to simply check for the presence of the swim method (i.e. canSwim()); rather than checking against the type*.
I appreciate it's sometimes hard to find simple real-world examples; but in this case you either need to find a better one or add a health warning: your isFish method is very likely to introduce hard to trace bugs in future and defeats the very purpose of using TS.
Apart from that I found the article useful ;)
* In the same way you should prefer 'feature detection' over 'browser detection'.
Hello ! As I said in another comment the aim of this example is to understand what is a Typeguard ! My example doesn't reflect the reality since as you said, Duck can be identificated as Fish !
In a real project you should use another way to make the difference between each class :)
In a real project you should use another way to make the difference between each class
Indeed; that was precisely my point: it's an ill-conceived example and demonstrates how not to use Typescript. There's little point demonstrating that functionality exists if you don't also demonstrate the thought processes required to use it properly.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I find your example of Typeguard a little problematic precisely because it is subject to fail in the case of "interface growth". Determining type based on the presence of a method looks really flaky to me. As already suggested a duck would be identified as a fish. In your example code it makes much more sense to simply check for the presence of the swim method (i.e.
canSwim()
); rather than checking against the type*.I appreciate it's sometimes hard to find simple real-world examples; but in this case you either need to find a better one or add a health warning: your
isFish
method is very likely to introduce hard to trace bugs in future and defeats the very purpose of using TS.Apart from that I found the article useful ;)
* In the same way you should prefer 'feature detection' over 'browser detection'.
Hello ! As I said in another comment the aim of this example is to understand what is a Typeguard ! My example doesn't reflect the reality since as you said, Duck can be identificated as Fish !
In a real project you should use another way to make the difference between each class :)
Thank you for your comment a lot !
Indeed; that was precisely my point: it's an ill-conceived example and demonstrates how not to use Typescript. There's little point demonstrating that functionality exists if you don't also demonstrate the thought processes required to use it properly.