3 ms·
> If you can pass a Cat to a Dog function, where is the better checking? If you have compatible method, fields and types, in a duck-typed ecosystem like Javasc
by dtech 7y ago
> If you can pass a Cat to a Dog function, where is the better checking?
If you have compatible method, fields and types, in a duck-typed ecosystem like Javascript it is a major boon that it is possible to interchange them, because it happens all the time in the ecosystem.
The standard way to do enforce exactly the right interface in typescript if you need to is to add a `type: "cat" | "dog"` field to your Animal interface and have the Cat interface have `type: "cat"`. If works well and is very similar to a JVM Class object or .NET Type object.
Structural typing, literal types and dependant types are major blessings to have available sometimes, and I'd really like languages to adopt some of Typescripts power and simplicity in this. So far I've only seen Julia have some of it, although Scala 3 also introduces some bits.
- blobs 7y agoWhatever words you use, it simply conflicts with basic JS and is a serious flaw. const cat = new Cat(); if (cat instanceof Dog) console.log('this should never be possible!'); What is this strange protective behavior towards TS, can we stick to logic please?
- redmorphium 7y agoinstanceof checks the prototype chain, which is a different concept from type. Prototype chains are dynamic and exist at runtime, while Typescript types are a static concept.
- kazinator 7y agoWhat is a boon is that I can write code that accesses obj.breed and have it work with any object that has a breed property. That has some downsides; it can be abused to create a ball of mud. However, a middle-of-the-road type check which insists that an object must have all of the properties of Dog, even ones you're not using, isn't very useful. It kills the above dynamism, and yet allows abuses to sneak through. You will not find that cats are being passed to Dog functions until you try to maintain Dog. And then you will discover that, oops, everything you add to Dog has to be replicated in Cat. Basically, a typecheck which says that an object coming in has to have all the properties of Dog might as well just be a subclass check. The smart way to ensure that a non-Dog class has all the properties of Dog is inheritance. A properly done static version of this structural type check would validate that the object being passed to the function doesn't have all the properties of a Dog, but that it has all the properties which just that function requires (including transitively: through any functions it calls).