Skip to content

thecodeaware/ts-interface-builder

Repository files navigation

Typescript Interface Builder

Build Status codecov MIT License

Builder pattern for typescript types.

Installation

npm install @thecodeaware/ts-interface-builder

Usage

import { builderOf } from '@thecodeaware/ts-interface-builder';

interface Input {
  label: string;
  value: number;
  title?: string;
}

const input: Input = builderOf<Input>().title('title').label('label').value(2).build();

// with default object
const inputWithDefaults: Input = builderOf<Input>({
  title: 'defaultTitle',
  label: 'defaultLabel',
  value: 1,
})
  .title('title')
  .value(2)
  .build();

Contribution

Feel free to add improvements. Remember about the tests!

npm install
npm run test

FAQ

  1. Why not API with with prefix like withLabel for label property?

It is possible with TS but it brings more edge cases.

export type TypeBuilder<T> = {
  [P in keyof T as `with${Capitalize<string & P>}`]: (arg: T[P]) => TypeBuilder<T>;
} & {
  build(): T;
};
  • Object with capitalized property.
  • Object with capitalized and non-capitalized property like label and Label.

About

Builder pattern for typescript interfaces

Resources

License

Stars

Watchers

Forks

Packages

No packages published