Stop Avoiding Classes in TypeScript

In TypeScript, developers often begin by defining the structure of their data using type definitions or interfaces, which is a powerful way to ensure type safety. However, as applications grow and become more complex, simply defining the shape of an object might not be enough to guarantee its consistent creation and behavior throughout the codebase. This often leads to situations where objects that are intended to be of a certain "type" might be missing crucial properties or have incorrect data, which can be difficult to track down and debug.

This lesson tackles the question of when and why to move beyond basic type definitions and embrace classes in TypeScript. It demonstrates how classes provide a more robust mechanism for defining object structure, enforcing type constraints, and ensuring consistent object creation. By establishing a clear blueprint for objects, classes not only improve compile-time type safety but also offer runtime benefits and better code organization, ultimately helping developers avoid common pitfalls associated with loosely structured objects in larger TypeScript projects.

Share with a coworker

Transcript

[00:00] If you create an object and you start reaching to create a type of that object, just go ahead and create a class instead. Because this way you'll have essentially a factory function which manages your types for you. Because any time you would come in and change a type in your class, it would automatically break when you try and create that object. And it's smart enough to know that the instance of that object would be incorrect as well. So I'll quickly undo all of that.

[00:25] And you also get the benefit of being able to quickly create new objects that perfectly match the class and you don't even have to think about it as a type of person or worrying about missing any properties because this will force you to pass in everything you need. If I remove zip I get an error. If I miss an argument I get an error. So classes can help protect you and the other developers from creating improper objects. Classes are also super easy to cut, create a new file, call it whatever, data.ts, to just export, paste, then switch over, then import.

[00:59] And they can live in their own file and serve as completely isolated ways of defining object structure and object types. Then when it comes time to even check if an object that was created is a type of this person you get access to instanceof. And instanceof is not a TypeScript feature that gets compiled away, it's a JavaScript feature which will actually check if Ben is a person. Again, forcing these objects to be created in a very specific way. And you don't have to use patterns that I'll see a lot like Ben type is a person or other conditional checking scenarios that happen when objects are not created with classes.