Typescript is a great and powerful tool for type checking but it could bother you if you don’t define your type according to business logic rules.

If your models don’t reflect business logic rules, after some time it will create a gap between what business logic says and how your code behaves.

Let’s explain this with an example.

We need to define a model for storing Person data. the rules and constraints are:

  • a person must have a first name with limited length 50
  • a person must have a last name with limited length 50
  • a person must have contact info. contact info could be Email or PostalCode or both.

It seems very reasonable to model the Person model like this.

type Person = {
     firstName: string
     lastName: string
     email?: string
     postalCode?: string

BUT there are some problems in this modeling.

  • firstName and lastName are not any string. they could not have any length, they should have a limited length of 50.
  • email is not any string. it should have some specific shape (has @ character and domain name in it)
  • postalCode is not any string. it should contain 10 digits.

how could we put these rules into our model?

#domain-modeling #business-logic #domain-model #domain-driven-design #typescript

Reflecting business logic rules into the domain models using typescript — Part 1
1.40 GEEK