In the previous article, we learned how to create self-documented types and models. but they were just types and didn’t have any functionality.
In this article, we are going to write some code that creates and validates those types.
At the end of this article, our types can be used in real-life projects.
The project source code is available here:
First, we need a typescript project. so let’s create it.
yarn init -y
yarn add --dev typescript ts-node
./node_modules/.bin/tsc --init
Then we create our types.
import {CustomTypeError} from "../exception/CustomTypeError";
export type String50 = {
kind: "String50",
value: string,
}
export const makeString50 = (arg: any): String50 => {
if (typeof arg === "string" && arg.length <= 50) {
return {
kind: "String50",
value: arg,
};
}
throw new CustomTypeError("String50", arg);
}
At the top, there is the type declaration. after that, there is the makeString50
function. this function accepts any
argument and tries to create String50
.
It checks if the argument type is a string
and its length is less than 50.
If the argument doesn’t satisfy the rules and constraint it will throw a CustomTypeError
exception.
And here is CustomTypeError
export class CustomTypeError extends Error {
constructor(type: string, value: any) {
super(`invalid value ${JSON.stringify(value)} provided for type ${type}`);
}
}
It is just a simple class for showing errors.
We use it in try catch
blocks to handle our custom type errors.
Let’s continue to define other types.
#domain-driven-design #business-logic #typescript #domain-modeling #domain-model