TinyTypes

A tiny library that brings Tiny Types to JavaScript and TypeScript

README

Tiny Types


TinyTypes is an npm module that makes it easy for TypeScript and JavaScript
projects to give domain meaning to primitive types. It also helps to avoid all sorts of bugs
and makes your code easier to refactor. Learn more.

Installation


To install the module from npm:

  1. ```
  2. npm install --save tiny-types
  3. ```

API Docs


API documentation is available at jan-molak.github.io/tiny-types/.

For Enterprise


TinyTypes are available as part of the Tidelift Subscription. The maintainers of TinyTypes and thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. If you want the flexibility of open source and the confidence of commercial-grade software, this is for you. Learn more.

Defining Tiny Types


An int on its own is just a scalar with no meaning. With an object, even a small one, you are giving both the compiler

and the programmer additional information  about what the value is and why it is being used.
>

Single-value types


To define a single-value `TinyType` - extend from `TinyTypeOf()`:

  1. ```typescript
  2. import { TinyTypeOf } from 'tiny-types';

  3. class FirstName extends TinyTypeOf<string>() {}
  4. class LastName  extends TinyTypeOf<string>() {}
  5. class Age       extends TinyTypeOf<number>() {}
  6. ```
Every tiny type defined this way has
value of type T, which you can use to access the wrapped primitive value. For example:

  1. ```typescript
  2. const firstName = new FirstName('Jan');

  3. firstName.value === 'Jan';
  4. ```

Equals


Each tiny type object has an equals method, which you can use to compare it by value:

  1. ```typescript
  2. const
  3.     name1 = new FirstName('Jan'),
  4.     name2 = new FirstName('Jan');

  5. name1.equals(name2) === true;
  6. ```

ToString


An additional feature of tiny types is a built-in toString() method:

  1. ```typescript
  2. const name = new FirstName('Jan');

  3. name.toString() === 'FirstName(value=Jan)';
  4. ```

Which you can override if you want to:

  1. ```typescript
  2. class Timestamp extends TinyTypeOf<Date>() {
  3.     toString() {
  4.         return `Timestamp(value=${this.value.toISOString()})`;
  5.     }
  6. }

  7. const timestamp = new Timestamp(new Date());

  8. timestampt.toString() === 'Timestamp(value=2018-03-12T00:30:00.000Z))'
  9. ```

Multi-value and complex types


If the tiny type you want to model has more than one value,
or you want to perform additional operations in the constructor,
extend from TinyType directly:

  1. ```typescript
  2. import { TinyType } from 'tiny-types';

  3. class Person extends TinyType {
  4.     constructor(public readonly firstName: FirstName,
  5.                 public readonly lastName: LastName,
  6.     ) {
  7.         super();
  8.     }
  9. }

  10. ```

You can also mix and match both of the above definition styles:

  1. ```typescript
  2. import { TinyType, TinyTypeOf } from 'tiny-types';

  3. class UserName extends TinyTypeOf<string>() {}

  4. class Timestamp extends TinyTypeOf<Date>() {
  5.     toString() {
  6.         return `Timestamp(value=${this.value.toISOString()})`;
  7.     }
  8. }

  9. abstract class DomainEvent extends TinyTypeOf<Timestamp>() {}

  10. class AccountCreated extends DomainEvent {
  11.     constructor(public readonly username: UserName, timestamp: Timestamp) {
  12.         super(timestamp);
  13.     }
  14. }

  15. const event = new AccountCreated(new UserName('jan-molak'), new Timestamp(new Date()));
  16. ```

Even such complex types still have both the equals and toString methods:

  1. ```typescript
  2. const
  3.     now = new Date(2018, 2, 12, 0, 30),
  4.     event1 = new AccountCreated(new UserName('jan-molak'), new Timestamp(now)),
  5.     event2 = new AccountCreated(new UserName('jan-molak'), new Timestamp(now));
  6.     
  7. event1.equals(event2) === true;

  8. event1.toString() === 'AccountCreated(username=UserName(value=jan-molak), value=Timestamp(value=2018-03-12T00:30:00.000Z))'
  9. ```

Guaranteed runtime correctness


The best way to guarantee runtime correctness of your domain models is to ensure that no tiny type can ever hold invalid data at runtime.
This way, when a function receives an instance of a tiny type, it does not need to perform any checks on it and can simply trust that
its value is correct. OK, but how do you guarantee that?

Let me show you an example.

Imagine that upon registering a customer on your website you need to ask them their age.
How would you model the concept of "age" in your system?

You might consider using a [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) for this purpose:
  1. ```typescript
  2. const age = 35;
  3. ```
However, this is far from ideal as "age" is not just _any_ number: it can't be negative, it has to be an integer, and it's highly unlikely that your customers would ever be [253-1 years old](https://www.ecma-international.org/ecma-262/10.0/index.html#sec-ecmascript-language-types-number-type).

All that means that there are certain _rules_ that an object representing "age" needs to obey, certain _constraints_ that its value has to meet in order to be considered valid.

You might have already guessed that my recommendation to you would be to define a tiny type representing Age, but not just that.
You should also take it a step further and use the [ensure](https://jan-molak.github.io/tiny-types/function/index.html#static-function-ensure) function together with other [predicates](https://jan-molak.github.io/tiny-types/identifiers.html#predicates) to describe the constraints the underlying value has to meet:

  1. ```typescript
  2. import { TinyType, ensure, isDefined, isInteger, isInRange } from 'tiny-types'

  3. class Age extends TinyType {
  4.   constructor(public readonly value: number) {
  5.     ensure('Age', value, isDefined(), isInteger(), isInRange(0, 125));
  6.   }
  7. }
  8. ```

With a tiny type defined as per the above code sample you can eliminate entire classes of errors. You also have one place in your
system where you define what "age" means.