0.0.15 • Published 4 years ago
ts-object-builder v0.0.15
object-builder
Simple Typesafe Object builder for Typescript
Installation
npm install --save-dev ts-object-builder
Usage
Build with fixed values
class Sample {
numericField: number;
stringField: string;
}
class SampleObjectBuilder extends ObjectBuilder<Sample> {
constructor() {
super(Sample);
}
}
const obj = new SampleObjectBuilder()
.with('numericField', 123)
.with('stringField', 'awesome string')
.build();
// Builds:
// {
// numericField: 123,
// stringField: 'awesome string'
// }
Build with functions to provide value
const obj = new SampleObjectBuilder()
.with('numericField', 123)
.with('stringField', () => 'awesome string')
.build();
// Builds:
// {
// numericField: 123,
// stringField: 'awesome string'
// }
Build multiple
const objList = new SampleObjectBuilder()
.with('numericField', () => Math.random() * 1000000)
.with('stringField', 'awesome string')
.buildList(2);
// Builds:
// [
// {
// numericField: 123,
// stringField: 'awesome string'
// },
// {
// numericField: 234,
// stringField: 'awesome string'
// }
// ]
Build multiple with index
const objList = new SampleObjectBuilder()
.with('numericField', () => Math.random() * 1000000)
.with('stringField', (index: number) => `value ${index}`)
.buildList(2);
// Builds:
// [
// {
// numericField: 123,
// stringField: 'value 0'
// },
// {
// numericField: 234,
// stringField: 'value 1'
// }
// ]
Build without certain fields
const objList = new SampleObjectBuilder()
.with('numericField', () => Math.random() * 1000000)
.with('stringField', 'awesome string')
.without('stringField')
.buildList(2);
// Builds:
// [
// {
// numericField: 123
// },
// {
// numericField: 234
// }
// ]