0.3.0 • Published 3 years ago

typescript-object-builder v0.3.0

Weekly downloads
29
License
MIT
Repository
github
Last release
3 years ago

ObjectBuilder

npm.io

ObjectBuilder is a type-safe implementation of Builder pattern with smart type inference.

Usage

ObjectBuilder.new

import { ObjectBuilder } from 'typescript-object-builder';

type Endpoint = { url: string; method: string; description?: string };

const endpoint = ObjectBuilder.new<Endpoint>()
  .with('url', `/status/`)
  .with('method', 'GET')
  .with('description', 'Health check')
  .build(); /* OK - all of the required fields are set - `build` method becomes available */

const invalidEndpoint = ObjectBuilder.new<Endpoint>()
  .with('url', `/status/`)
  .with('description', 'Health check')
  .build(); /* Error - build method is not available since one of the required fields is not set */

ObjectBuilder.fromBase

import { ObjectBuilder } from 'typescript-object-builder';

type Endpoint = { url: string; method: string; description?: string };

const base = { url: '/status', description: 'Health check' };

const endpoint = ObjectBuilder.fromBase<Endpoint, typeof base>(base)
  .with('method', 'GET')
  .build(); /* OK - all of the required fields are set (via base object and `with`) */

const invalidEndpoint = ObjectBuilder.fromBase<Endpoint, typeof base>(base)
  .with('description', 'desc')
  .build(); /* Error - build method is not available since one of the required fields is not set */

ObjectBuilder.basedOn

import { ObjectBuilder } from 'typescript-object-builder';

type Endpoint = { url: string; method: string; description?: string };

const base = { url: '/status', method: 'GET' };

const rewrittenEndpoint = ObjectBuilder.basedOn<Endpoint>(base)
  .with('method', 'GET')
  .with('description', 'GET /status')
  .with('url', '/status')
  .build(); /* Allows to take a base object and rewrite some or all of the properties */

Utility types

ObjectBuilder.PickNonOptionalFieldsKeys

import type { PickNonOptionalFieldsKeys } from 'typescript-object-builder';

type Endpoint = { url: string; method: string; description?: string };

type T = PickNonOptionalFieldsKeys<Endpoint>; /* T is "url" | "method" */

ObjectBuilder.PickNonOptionalFields

import type { PickNonOptionalFields } from 'typescript-object-builder';

type Endpoint = { url: string; method: string; description?: string };

type T = PickNonOptionalFields<Endpoint>; /* T is { url: string; method: string; } */

Features

  • type-safe - it doesn't allow to call build method unless all non optional fields have been set
  • smart type inference - builder offers (via autocomplete) to provide only those fields which have not been set yet
0.3.0

3 years ago

0.2.0

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago