Re:TypeScript’s quirks: How inconsistencies make the languag...
by kazinator on Monday February 03, 2020 @06:22PM
(#22230487)
What 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).
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).