🧩 TypeScript utility type in order to ensure to return only properties (not methods) containing values in primitive types such as number or boolean (not Value Objects)

Overview

🧩 TypeScript Primitives type

Codely Open Source CodelyTV Courses

TypeScript utility type in order 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 😊

πŸ‘€ Usage example

You can have a domain entity such as the following Course:

import { CourseId } from "./CourseId";
import { CourseTitle } from "./CourseTitle";

export class Course {
  constructor(readonly courseId: CourseId, readonly 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:

  • We want to avoid including methods such as the thisFunctionShouldNotBeIncludedInTheToPrimitives one, so the transformation should only include properties.
  • We want to flatten or unwrap encapsulated properties such as the courseId and courseTitle ones. They are modelled 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(readonly courseId: CourseId, readonly 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 straighforward way! 🌈

πŸ‘ How to install

  • Npm: npm install |--save-dev @codelytv/primitives-type
  • Yarn: yarn add -D @codelytv/primitives-type

πŸ‘Œ  Codely Code Quality Standards

Publishing this package we are committing ourselves to the following code quality standards:

  • 🀝 Respect Semantic Versioning: No breaking changes in patch or minor versions
  • 🀏  No surprises in transitive dependencies: Use the bare minimum dependencies needed to met the purpose
  • 🎯  One specific purpose to met without having to carry a bunch of unnecessary other utilities
  • βœ…  Tests as documentation and usage examples
  • πŸ“– Well documented ReadMe showing how to install and use
  • βš–οΈ License favoring Open Source and collaboration

πŸ”€ Related utilities and resources

☝️ Learning resources

πŸ”· TypeScript skeletons

🌈 TypeScript Domain-Driven Design repositories

🎯 Other languages Domain-Driven Design repositories

You might also like...

πŸš€ Transition number values using easing functions

πŸš€ Transition number values using easing functions

react-transition-value Transition / Animate number values using easing functions See Demos ⚑️ Getting started npm i react-transition-value import {

Dec 15, 2022

A simple in-memory key-value cache for function execution, allowing both sync and async operations using the same methods

A simple in-memory key-value cache for function execution, allowing both sync and async operations using the same methods. It provides an invalidation mechanism based both on exact string and regex.

Dec 15, 2022

A library for boolean aliases to help you make your code more confusing and make your coworkers hate you.

yup-nope A library for boolean aliases to help you make your code more confusing and make your coworkers hate you. Installation Using npm: npm install

Dec 10, 2022

An idiomatic way to enforce values not to be null nor undefined, with first-class support for TypeScript

nullthrows An idiomatic way to enforce values not to be null or undefined, with first-class support for TypeScript. Very lightweight with no dependenc

Jul 23, 2022

Tiny JavaScript library (1kB) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Zero dependency tiny JavaScript library (1kB bytes) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Nov 8, 2022

Very tiny function that checks if an object/array/value is shaped like another, with TypeScript type refining.

@suchipi/has-shape Very tiny (~200B before minification/compression) function that checks if an object/array/value is shaped like another, with TypeSc

Aug 13, 2022

This simple extension can automatically load NBN availability information for properties on realestate.com.au & domain.com.au including technology type, maximum line speed, and co-existance status if available.

This simple extension can automatically load NBN availability information for properties on realestate.com.au & domain.com.au including technology type, maximum line speed, and co-existance status if available.

NBN Availability Check Chrome Extension This simple extension can automatically load NBN availability information for properties on realestate.com.au

Aug 17, 2022

A jQuery plugin that works in harmony with animate.css in order to enable animations only when content comes into view.

jQuery AniView A jQuery plugin that works in harmony with animate.css in order to enable animations only when content comes into view. Now supports v4

Sep 10, 2022

Tiny and fast utility to extract all possible values for a given enum.

Tiny (208B) and fast utility to extract all possible values for a given enum.

Apr 18, 2022
Comments
  • Support nullable properties

    Support nullable properties

    When I tried to use this type in one of my projects, I noticed that it does not support nullable properties.

    I added a Nullable type inside the Primitives.ts file, and then used it as the generic in Properties, so the new Primitives type looks like this:

    type Nullable<T> = T | null;
    export type Primitives<T> = ValueObjectValue<Properties<Nullable<T>>>;
    

    To test it, I added a nullable property to Course and create an specific test for this feature. This addition forced me to also change the existing test.

    opened by xetxeberria 2
  • Nullable attributes

    Nullable attributes

    Hi,

    I have tried to use the library but I have problems with null values.

    In a class with some attribute of type VideoName | null, the return type is VideoName | null when it should be string | null

    Is it possible to fix this?

    Regards

    opened by DiV666 3
Owner
CodelyTV
Code examples for our software development videos and courses
CodelyTV
Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator Types generator is a utility tool that will help User to create TS Interfaces from JSON. All you have to do is paste your single objec

Vineeth.TR 16 Dec 6, 2022
A little utility type package that allows you to access the current TypeScript version from your types.

@phryneas/ts-version A little utility type package that allows you to access the current TypeScript version from your types. import { TSVersion } from

Lenz Weber-Tronic 11 Sep 4, 2022
Fix for Object.hasOwnProperty, which normally just returns a boolean, which is not good when you care about strong typing.

Welcome to ts-has-own-property ?? Fix for Object.hasOwnProperty, which normally just returns a boolean, which is not good when you care about strong t

Funtal Foundation 1 Jul 4, 2022
Combine type and value imports using Typescript 4.5 type modifier syntax

type-import-codemod Combines your type and value imports together into a single statement, using Typescript 4.5's type modifier syntax. Before: import

Ian VanSchooten 4 Sep 29, 2022
Simple Solid primitive unit test utility.

solid-primitive-test-util Simple Solid primitive unit test utility. Install pnpm add solid-primitive-test-util -D Example Basic Usage Let's say we hav

Robert Soriano 2 Mar 21, 2022
100% type-safe query builder for node-postgres :: Generated types, call any function, tree-shakable, implicit type casts, and more

⚠️ This library is currently in alpha. Contributors wanted! tusken Postgres client from a galaxy far, far away. your database is the source-of-truth f

alloc 54 Dec 29, 2022
Type predicate functions for checking if a value is of a specific type or asserting that it is.

As-Is Description As-Is contains two modules. Is - Type predicates for checking values are of certain types. As - Asserting values are of a certain ty

Declan Fitzpatrick 8 Feb 10, 2022
A lightweight (~2kB) library to create range sliders that can capture a value or a range of values with one or two drag handles

range-slider-input A lightweight (~2kB) library to create range sliders that can capture a value or a range of values with one or two drag handles. Ex

Utkarsh Verma 42 Dec 24, 2022
We are creating a Library that would ensure developers do not reinvent the wheel anymore as far as Authentication is concerned. Developers can easily register and download authentication codes that suits their need at any point.

#AuthWiki Resource Product Documentation Figma Database Schema First Presentation Live Link API Documentation Individual Contributions User Activity U

Zuri Training 17 Dec 2, 2022
Compile-time tests for types. Useful to make sure types don't regress into being overly-permissive as changes go in over time.

expect-type Compile-time tests for types. Useful to make sure types don't regress into being overly-permissive as changes go in over time. Similar to

Misha Kaletsky 82 Jan 8, 2023