4 ms·
Close, any objects with the same properties and types are compatible. The name of the properties and their types need to match. And this isn't always a good th
by slackingoff2017 9y ago
Close, any objects with the same properties and types are compatible. The name of the properties and their types need to match.
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.
- didibus 9y agoI see, sounds interesting. Are the names namespaced? And how would a method know its compatible? Do you type the properties a method needs instead of the object name?
- slackingoff2017 9y agoYou pretty much act as you do with regular type systems, rarely creating types that are compatible by accident. There is one place however where you use structural typing constantly. 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.
- didibus 9y agoHum, thanks for the info. I feel curious to try it out. I think names should be namespaced though, that could solve the issue of having a length or value named property. The namespace could distinguish between two values that aren't compatible for example. Though I guess if the types are precise enough, they could embed some of that.
- jwdunne 9y agoGiven an object with a length property with the type a method expects, is there ever a scenario where the method is incorrect? 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.
- slackingoff2017 9y agoThe type system is still working properly in that it will produce code that compiles and runs. For the developer such a behaviour can be misleading. This is compounded by IDE's with intellisense which will suggest passing random objects with the correct properties into the function.