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;
}