One reason I really like TypeScript is its Type system, it is practical and feature rich. Applying the types in right use cases can make our code cleaner and easier to maintain.

The purpose of this article is to share an example of code refactoring with type script discriminated union type and Generics.

The original code

This piece of code is to represent user roles and feature/permissions mapping, to build a user access matrix in an Angular App.

Image for post

The code above contains:

  1. FeatureAccess: A constant representing two features (“UserManagement” and “Order”) and their permissions.
  2. SalesRole: A Role class that describes the list of permissions a Sales user has and “canAccess” method based on that.

#javascript #typescript #programming

Use Cases For TypeScript Discriminated Union Types and Generics
1.45 GEEK