3 ms·
My personal rule of thumb: - If I'm dealing with pure data (of varying sources) I use interfaces - If I'm modelling something which has an identity and state
by Matthias247 9y ago
My personal rule of thumb:
- If I'm dealing with pure data (of varying sources) I use interfaces
- If I'm modelling something which has an identity and state (and probably attached methods to modify the state) I'm using a class.
Wrote a bit more about it here: https://stackoverflow.com/questions/40591413/interface-and-class-in-typescript/40595930#40595930 https://stackoverflow.com/questions/40591413/interface-and-c...
- Parsyval 9y ago"interfaces don't have a runtime representation" I was looking for a good way to say that while writing the article, this is a very good way ! Thanks Also I like that you think about the use of instanceof, I didn't really think of that, but some devs use this condition intensively.
- electrotype 9y agoI agree. Using classes for entities allows you to use libraries such as https://github.com/typestack/class-transformer https://github.com/typestack/class-transformer And allows you to use "instanceof". User defined type guards for interfaces are hackish at best.
- Legogris 9y ago"instaceof" is something I would advise against for any code that might be called from another module. If you have different modules requiring that same module and they for whatever reason (webpack behavior, node not deduping properly, npm link, different versions, etc), that instanceof will fail and the caller will be left scratching their head as to why their object fails the check. In JavaScript (and by extension TypeScript), you are best left to duck-typing for run-time checks.
- leshow 9y agoWhy don't you use a type alias instead of an interface for pure data?