by slackingoff2017 · 9y ago · 0 comments
This is known as structural typing and TypeScript does exactly this. Two objects with the same properties are the same.
This usually works well, but there are a few issues with this. Number one is related to optimization. The type system that results from using structural typing is unsound. This doesn't matter for typescript since it compiled down to JavaScript which has no types anyways, but for a typical VM executed language there's many optimizations the compiler can't do.
The second issue with structural typing is what I like to call the "mixin problem". If you get too flexible with composition it becomes close to having no type system at all.
Like is all things which only have two integer properties considered the same?
{ Int age; Int weight; }
Would be equal to:
{ Int x; Int y; }
?
And this isn't always a good thing. If you have a function dealing with the property 'length' or 'value' for instance, you might as well have no type system because Typescript will allow you to pass in any object with those properties which is almost anything.
While the code will still compile and run like this the type system has failed its purpose of preventing developers from using the wrong types.
I'm trying to wrap my head around it: if a method needs only the length property, which is an unsigned int, is there any good reason why it shouldn't accept any object that has that property?
It appears at first that this is a good quality: the code is general whilst obviously avoiding any type errors, including null/undefined errors.
TypeScript is a superset of JavaScript and using "options" objects as method parameters is a common pattern. These options objects are synonymous with anonymous classes and don't have a name, only a shape. Structural typing is one of the strategies TypeScript uses to maintain compatibility with patterns in JavaScript that use these nameless objects.
There are no namespaces. Methods are compatible if they take the same or a subset of the parameters. Objects need to have matching property names and values.