TypeScript 3.7 added support for Assertions in control flow analysis and the
asserts type-predicate.
A recurring pattern is to throw when a value fails validation:
const { body } = request;
if (!isBodyExpectedType(body)) {
throw new Error(...);
}
useBody(body)
function useBody(body: ExpectedType) { ... }And dealing with rejections may create even more recurring boilerplate:
const { body } = request;
const rejections: ValidationRejection[] = [];
if (!isBodyExpectedType(body, rejection => rejections.push(rejection))) {
// Do something with the rejections:
console.debug(rejections)
throw new Error(...);
}
useBody(body)
function useBody(body: ExpectedType) { ... }Using TypeScript's Assertions in control flow analysis, we can encapsulate that pattern into a function:
const { body } = request;
validateBody(body)
useBody(body)
function validateBody(value: unknown): asserts value is ExpectedType {
const rejections: ValidationRejection[] = [];
if (!isBodyExpectedType(body, rejection => rejections.push(rejection))) {
// Do something with the rejections:
console.debug(rejections)
throw new Error(...);
}
}
function useBody(body: ExpectedType) { ... }Using the function assertBy we can remove even more boilerplate, and effortlessly
create assertion-functions.
const { body } = request;
// Assertion methods must be explicitly typed.
const validateBody: Assertion<ExpectedType> = assertBy(
isBodyExpectedType,
(value, rejections) => {
// Do something with the rejections:
console.debug(rejections)
return new Error(...);
}
);
validateBody(body)
useBody(body)
function useBody(body: ExpectedType) { ... }The validated type of the provided type-validation.
Type-validation for the asserted type.
Type: AnyTypeValidation<T>
A function that creates an error for a given value and rejections.
Type: (val: unknown, rejections: ValidationRejection[]) => unknown
An assertion function of type (value: unknown) => asserts value is T.