3 ms·
So the real reason is "because of the limitation of the structural typing instead of the nominal one"?
by _ZeD_ 3y ago
So the real reason is "because of the limitation of the structural typing instead of the nominal one"?
- layer8 3y agoNo, the reason is that the properties enumeration works on the dynamic type and not on the static type.
- recursive 3y agoYou can do this with all nominal types too. Imagine types Parent and Child. Child has more properties, yet satisfies the contract of Parent. If you enumerate all the properties of some arbitrary Parent p, you may get some extra properties.
- _ZeD_ 3y agothat's not how nominal types work: the properties looped over will be only the one of Parent
- bazoom42 3y agoIn Java or C# you would need to use reflection to loop over the members of an object, but AFAIK this would yield the members of the current instance, not the nominal type.
- recursive 3y agoNo, sorry, you're not right. Here's some C# you can run in your browser. https://dotnetfiddle.net/ZeSNkA https://dotnetfiddle.net/ZeSNkA
- afiori 3y agoThe article says that it is because of structural typing, but actually it is because in TS object subtype automatically. It has little to do with structural typing per se; you would have the same behaviour with nominal classes* and inheritance. * this is likely why OOP languages have _final_ classes
- bazoom42 3y agoNo, it is unrelated to the nominal/structural distinction. It is a logical but perhaps counter-intuitive consequence of supporting reflection in a statically typed language. Most languages avoid the issue by either not supporting reflection or by having reflection be untyped (eg returning all members as “object” and let the client cast to the appropriate type). Typescript tries to support type-safe reflection, but this means the types have to be wider than you would intuitively expect, in order to take subtypes into account.