Skip to content

Commit

Permalink
feat: add Validator#is
Browse files Browse the repository at this point in the history
  • Loading branch information
kyranet committed Aug 29, 2022
1 parent bb91ddd commit 2ce75c2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/validators/BaseValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ export abstract class BaseValidator<T> {
return this.constraints.reduce((v, constraint) => constraint.run(v).unwrap(), this.handle(value).unwrap()) as R;
}

public is<R extends T = T>(value: unknown): value is R {
return this.run(value).isOk();
}

/**
* Sets if the validator should also run constraints or just do basic checks.
* @param isValidationEnabled Whether this validator should be enabled or disabled. You can pass boolean or a function returning boolean which will be called just before parsing.
Expand Down
16 changes: 16 additions & 0 deletions tests/validators/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@ import { CombinedError, ExpectedValidationError, Result, s, ValidationError } fr
import { expectClonedValidator, expectError, expectModifiedClonedValidator } from '../common/macros/comparators';

describe('BaseValidator', () => {
describe('is', () => {
test("GIVEN any value THEN it's narrowed to schema type", () => {
const predicate = s.string;

const value = 'Hello there' as string | null;
const is = predicate.is(value);

expect(is).toBe(true);
if (is) {
expect<string>(value);
} else {
expect<null>(value);
}
});
});

describe('optional', () => {
const optionalPredicate = s.string.optional;

Expand Down

0 comments on commit 2ce75c2

Please sign in to comment.