TypeSafe object generation with smart type inference.
npm install typescript-object-builder
ObjectBuilder is a type-safe implementation of Builder pattern with smart type inference.
ObjectBuilder.new
``typescript
import { ObjectBuilder } from 'typescript-object-builder';
type Endpoint = { url: string; method: string; description?: string };
const endpoint = ObjectBuilder.new
.with('url', /status/)build
.with('method', 'GET')
.with('description', 'Health check')
.build(); / OK - all of the required fields are set - method becomes available /
const invalidEndpoint = ObjectBuilder.new
.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
`typescript
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
.with('method', 'GET')
.build(); / OK - all of the required fields are set (via base object and with) /
const invalidEndpoint = ObjectBuilder.fromBase
.with('description', 'desc')
.build(); / Error - build method is not available since one of the required fields is not set /
`
ObjectBuilder.basedOn
`typescript
import { ObjectBuilder } from 'typescript-object-builder';
type Endpoint = { url: string; method: string; description?: string };
const base = { url: '/status', method: 'GET' };
const rewrittenEndpoint = ObjectBuilder.basedOn
.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 /
`
ObjectBuilder.PickNonOptionalFieldsKeys
`typescript
import type { PickNonOptionalFieldsKeys } from 'typescript-object-builder';
type Endpoint = { url: string; method: string; description?: string };
type T = PickNonOptionalFieldsKeys
`
ObjectBuilder.PickNonOptionalFields
`typescript
import type { PickNonOptionalFields } from 'typescript-object-builder';
type Endpoint = { url: string; method: string; description?: string };
type T = PickNonOptionalFields
``
- 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