5 ms·
I'm curious, what do you find are the advantages of structural typing?
by rwallace 6y ago
I'm curious, what do you find are the advantages of structural typing?
- ragnese 6y agoI assume, from their statement, it's simply the ergonomics of not having to explicitly name ad-hoc sum types. Which I do agree goes a long way in ergonomics and reduced friction for leveraging the type system.
- smt88 6y agoWith nominal type systems, you have to worry about explicitly associating types with one another. With structural typing, you can have types that satisfy a type requirement incidentally. This helps you to write in less coupled code. For example, let's say you have the `walk(Walker walker, int distance)` function. With nominal typing, you have to create the `Walker` interface, class, or trait, and then anything that can walk explicitly implement/extend it. With structural typing (let's use TS as an example), you can say, `type Walker = {legs: Number}`. Then any object with a property called `legs` with a `Number` type value will satisfy the first argument of my `walk` function. This is a trivial example, but it becomes extremely powerful and useful in large code bases. The compiler can start telling you exactly how you need to refactor your code to make it work again. And you don't have to keep every data structure in your head when you're designing your code. You can just say, "OK, this object is a cat. It has fur, legs, and a tail." It can be a simple data structure, without worrying about how it relates to other objects and methods.