typescript-object-builder
TypeScript icon, indicating that this package has built-in type declarations

0.3.0 • Public • Published

ObjectBuilder

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

Dependencies (0)

    Dev Dependencies (17)

    Package Sidebar

    Install

    npm i typescript-object-builder

    Weekly Downloads

    1,621

    Version

    0.3.0

    License

    MIT

    Unpacked Size

    42 kB

    Total Files

    23

    Last publish

    Collaborators

    • anton-kravchenko