Skip to content

Latest commit

 

History

History
92 lines (83 loc) · 3.09 KB

smart-constructor.md

File metadata and controls

92 lines (83 loc) · 3.09 KB

Smart Constructor

A smart constructor is a function that creates safe types.

  • It calls one or more data guarantees to validate its inputs.
  • It rejects any input data that isn't within the range / specification of the safe type.

For example:

class MediaType extends ValueObject<string> {
    // this is a smart constructor
    public constructor(input: string) {
        // if `input` doesn't conform to the RFC spec
        // for a MediaType, it throws an Error
        mustBeMediaTypeData(input);

        // at this point, we know it's safe
        super(input);
    }
}

Despite the name, a smart constructor doesn't have to be a class constructor. It can be any function that creates types:

type Uuid = Branded<string, "@safelytyped/uuid">;

// `makeUuid()` is a smart constructor too
function makeUuid(input: string): Uuid {
    mustBeUuidData(input);
    return input as Uuid;
}