Primitives type
<a href="https://github.com/CodelyTV"><img src="https://img.shields.io/badge/CodelyTV-OS-green.svg?style=flat-square" alt="Codely Open Source"/></a>
<a href="https://pro.codely.com"><img src="https://img.shields.io/badge/CodelyTV-PRO-black.svg?style=flat-square" alt="CodelyTV Courses"/></a>
TypeScript utility type to ensure to return only properties (not methods) containing values in primitive types such as number or boolean (not Value Objects).
Take a look, play and have fun with this. Stars are welcome 😊
You can have a domain entity such as the following Course:
import { CourseId } from "./CourseId";
import { CourseTitle } from "./CourseTitle";
export class Course {
constructor(public courseId: CourseId, public courseTitle: CourseTitle) {}
updateTitle(newCourseTitle: CourseTitle): void {
this.courseTitle = newCourseTitle;
}
someOtherMethodWithDomainLogic(): void {
// some algorithm
}
}
When we want to have a toPrimitives method in order to pass an instance of the Course class between architectural layers, so the thing we want pass around should be to serialized/marshalled in a way that only containings primitive values such as:
{
"courseId": "25658f31-2da1-4942-8b58-88aeacc79860",
"courseTitle": "🚜 TypeScript Avanzado: Más allá de any"
}
That is:
thisFunctionShouldNotBeIncludedInTheToPrimitives one, so the transformation should only include properties.courseId and courseTitle ones. They are modeled as Value Objects (CourseId and CourseTitle classes), so the transformation or flatten should only include properties in a recursive manner.That is exactly what our Primitives<T> utility type guarantees. Let's add it! 💪
import { Primitives } from "@codelytv/primitives-type";
import { CourseId } from "./CourseId";
import { CourseTitle } from "./CourseTitle";
export class Course {
constructor(public courseId: CourseId, public courseTitle: CourseTitle) {}
updateTitle(newCourseTitle: CourseTitle): void {
this.courseTitle = newCourseTitle;
}
someOtherMethodWithDomainLogic(): void {
// some algorithm
}
toPrimitives(): Primitives<Course> {
return {
courseId: this.courseId.value,
courseTitle: this.courseTitle.value,
};
}
}
Done! ✌️
The Primitives<Course> return type is ensuring all our restrictions in a very straightforward way! 🌈
npm install --save-dev @codelytv/primitives-typeyarn add -D @codelytv/primitives-typePublishing this package we are committing ourselves to the following code quality standards:
$ claude mcp add typescript-primitives-type \
-- python -m otcore.mcp_server <graph>