DEV Community

Discussion on: Functional design: smart constructors

Collapse
 
alerosa profile image
Alessandro Rosa

Hey Giulio, thanks for the great article!

I've been doing type-driven-design lately and I usually start by defining my domain logic with types. These types are usually made of refined types created by using smart constructors so I have full control on what's allowed in the domain logic.

For every type I have a "toDomain" function that takes a serializable dto (the interface to the "outside" world), let's say:

type PersonDto = {
  name: string,
  email: string
}

and returns a domain type (or some validation errors), something like this:

type Person = {
  name: ValidName, // created by a smart constructor
  email: ValidEmail // created by a smart constructor
}

This function involves quite a lot of code to transform and compose together the output from all the constructors (usually an Either) to get back a Validation so I was thinking about using use io-ts to accomplish the same thing.

In order to do that I would need to write all my types, even the domain ones, directly with io-ts which is something I'm not really sure about. What's your take on this?

Collapse
 
gcanti profile image
Giulio Canti

If you are not comfortable with deriving your domain models from io-ts values (understandable) the other option is code generation.
Also check out io-ts-codegen