|
|
|
|
|
by okbake
3010 days ago
|
|
I'm a fan of TypeScript's structural typing for this reason. I can define an interface that describes the shape of a "plain old object" (it's fields and their types), and then write functions that accept/returns an object of that interface. What's great about structural typing is I don't have to explicitly say "create a new object of this type", any object that satisfies the shape of the interface is valid (object literals for example). So you end up with the best of both worlds (in my opinion), where your state is made up of simple plain objects and you behaviors are just functions that accept simple plain objects, but you get all of the benefits of compile time static type checking because they are checked against the interface. |
|
interface SomethingWithAge{ age(); }
class Person{ age(); // age in years }
function classify( SomethingWithAge item ){ if( item.age() < 20 ){ print( 'young') } else{ print( 'old' ); } }
p = new Person( 33 ); classify( p ) // prints 'old'
class Message{ age(); // age in milliseconds }
c = new Message( 231443 );
classify( c ); // prints 'old'