logic
Logical combinators to compose guards and refinements in a type-safe way.
import { and, or, not, predicateToRefine, isString, isNumber } from 'is-kit';// Clearer name for the min-length ruleconst isLongLiteral = predicateToRefine<string>((value) => value.length > 3);const isLongString = and(isString, isLongLiteral);isLongString('abcd'); // trueisLongString('ab'); // falseisLongString(123 as unknown); // false// Type narrowing exampledeclare const maybeString: unknown;if (isLongString(maybeString)) {maybeString.toUpperCase(); // narrowed to string}or(isString, isNumber)('foo'); // truenot(isString)(123); // true
andAll
Chain multiple refinements after a precondition.
import { andAll, predicateToRefine, isString } from 'is-kit';// Chain multiple string checks with andAllconst minLen4 = predicateToRefine<string>((value) => value.length >= 4);const startsWithA = predicateToRefine<string>((value) => value.startsWith('A'));const isShortTitle = andAll(isString, minLen4, startsWithA);isShortTitle('Axel'); // trueisShortTitle('Bob'); // false (does not start with A)isShortTitle('ABC'); // false (length < 4)
guardIn
Adapt a guard to a broader domain and keep composing.
import { and, equals, guardIn, isNumber, predicateToRefine, struct } from 'is-kit';// Adapt a guard to a broader domain, then compose extra rulestype Circle = { kind: 'circle'; radius: number };type Shape =| { kind: 'rect'; width: number; height: number }| Circle;const isCircle = struct({kind: equals('circle' as const),radius: isNumber,});// isCircle: Guard<Circle>// Make it work as a refinement within Shapeconst circleInShape = guardIn<Shape>()(isCircle); // Refine<Shape, Circle>// Add a runtime-only rule (type stays Circle)const positiveRadius = predicateToRefine<Circle>((circle) => circle.radius > 0);const validCircle = and(circleInShape, positiveRadius);const shapeCircleValid: Shape = { kind: 'circle', radius: 10 };const shapeCircleNegativeRadius: Shape = { kind: 'circle', radius: -1 };const shapeRect: Shape = { kind: 'rect', width: 8, height: 5 };validCircle(shapeCircleValid); // truevalidCircle(shapeCircleNegativeRadius); // false (radius not positive)validCircle(shapeRect); // false (not a circle)