Skip to content

Commit

Permalink
Merge branch 'yousef-s-predicate-instance-of'
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-molak committed Oct 8, 2018
2 parents 54179dc + 4cee120 commit 5f50979
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
33 changes: 33 additions & 0 deletions spec/predicates/isInstanceOf.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'mocha';
import { given } from 'mocha-testdata';

import { ensure, isInstanceOf, TinyType } from '../../src';
import { expect } from '../expect';

describe('predicates', () => {

/** @test {isInstanceOf} */
describe('::isInstanceOf', () => {
class Birthday extends TinyType {
constructor(public readonly value: Date) {
super();

ensure('Birthday', value, isInstanceOf(Date));
}
}

it('ensures that the argument is an instance of Date', () => {
expect(() => new Birthday(new Date())).to.not.throw; // tslint:disable-line:no-unused-expression
});

given(
'2018-10-10',
undefined,
null,
{},
'string',
).it('complains if the value does not meet the predicate', (value: any) => {
expect(() => new Birthday(value)).to.throw(`Birthday should be instance of Date`);
});
});
});
1 change: 1 addition & 0 deletions src/predicates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export * from './isLessThanOrEqualTo';
export * from './isNumber';
export * from './isOneOf';
export * from './isString';
export * from './isInstanceOf';
export * from './or';
export * from './Predicate';
export * from './property';
20 changes: 20 additions & 0 deletions src/predicates/isInstanceOf.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Predicate } from './Predicate';

/**
* @desc Ensures that the `value` is an instance of `type`
*
* @example
* import { ensure, isInstanceOf, TinyType } from 'tiny-types';
*
* class Birthday extends TinyType {
* constructor(public readonly value: Date) {
* ensure('Date', value, isInstanceOf(Date));
* }
* }
*
* @param {Constructor<T>} type
* @returns {Predicate<T>}
*/
export function isInstanceOf<T>(type: { new (...args: any[]): T }): Predicate<T> {
return Predicate.to(`be instance of ${type.name}`, (value: T) => value instanceof type);
}

0 comments on commit 5f50979

Please sign in to comment.