0.1.3 • Published 5 years ago

ts-shallow-object-schema v0.1.3

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

TS Object Schema

Quick shallow object schema for strict TS types with 0 dependencies.

License TypeScript

Usage

import * as assert from 'assert';
import validateObject from 'ts-shallow-object-schema';

const testData: unknown = {
  testString: 'hello',
  testInt: 5,
  testObj: {
    a: 'a',
    b: 1,
  },
  testArr: [1, 2, 3],
};

interface ITest {
  testString: string;
  testInt: number;
  testObj: object;
  testArr: number[];
  testOptional?: number;
}

const lengthValidator: (data: ITest) => boolean = (data) => data.testArr.length === 3;

const testSchema: Schema<ITest> = [{
  key: 'testString',
  type: 'string',
}, {
  key: 'testInt',
  type: 'number',
}, {
  key: 'testObj',
  type: 'object',
}, {
  key: 'testArr',
  type: 'array',
  customValidator: lengthValidator,
}, {
  key: 'testOptional',
  type: 'number',
  optional: true,
}];


assert.strictEquals(validateObject(testSchema, testData), true); // true

const otherSchema: Schema<ITest> = [{
  key: 'missingKey',
  type: 'string',
}, ...testSchema];

assert.strictEquals(validateObject(otherSchema, testData), false); // true
0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago