ts-code-contracts 

Design by contract with TypeScript.
Installation & Usage
npm i ts-code-contracts
Requires TypeScript^3.7
You can now import the following functions from 'ts-code-contracts'
:
Make sure to checkout the examples in the documentation below
or refer to the test cases
and typing assistance!
Contracts are really just handy shorthands to throw an error, if the given condition is not met.
And yet they greatly help the compiler and the readability of your code.
requires
Use it to validate preconditions, like validating arguments.
Throws a PreconditionError
if the condition
is false
.
function requires(
condition: boolean,
message: string = 'Unmet precondition'
): asserts condition;
condition
- the condition that should be true
message
- an optional message for the error
Example:
function myFun(name: string) {
requires(name.length > 10, 'Name must be longer than 10 chars');
}
requiresNonNullish
A variation of requires
that returns the given value unchanged if it is not null
or undefined
.
Throws a PreconditionError
otherwise.
function requiresNonNullish<T>(
value: T,
message = 'Value must not be null or undefined'
): NonNullable<T>;
value
- the value that should not be null
or undefined
message
- an optional message for the error
Example:
function myFun(name: string | null) {
const nameNonNull = requiresNonNullish(name, 'Name must be defined');
nameNonNull.toUpperCase();
}
checks
Use it to check for an illegal state.
Throws a IllegalStateError
if the condition
is false
.
function checks(
condition: boolean,
message = 'Callee invariant violation'
): asserts condition;
condition
- the condition that should be true
message
- an optional message for the error
Example:
class Socket {
private isOpen = false;
send(data: Data) {
check(this.isOpen, 'Socket must be open');
}
open() {
this.isOpen = true;
}
}
checksNonNullish
A variation of checks
that returns the given value unchanged if it is not null
or undefined
.
Throws a IllegalStateError
otherwise.
function checksNonNullish<T>(
value: T,
message = 'Value must not be null or undefined'
): NonNullable<T>;
value
- the value that should not be null
or undefined
message
- an optional message for the error
Example:
class Socket {
data: Data | null = null;
send() {
const validData = checksNonNullish(this.data, 'Data must be available');
validData.send();
}
}
ensures
Use it to verify that your code behaved correctly.
Throws a PostconditionError
if the condition
is false
.
function ensures(
condition: boolean,
message = 'Unmet postcondition'
): asserts condition;
condition
- the condition that should be true
message
- an optional message for the error
Example:
function myFun() {
createPerson({ id: 0, name: 'John' });
const entity = findById(0);
return ensures(isDefined(entity), 'Failed to persist entity');
}
ensuresNonNullish
A variation of ensures
that returns the given value unchanged if it is not null
or undefined
.
Throws a PostconditionError
otherwise.
function ensuresNonNullish<T>(
value: T,
message = 'Value must not be null or undefined'
): NonNullable<T>;
value
- the value that should not be null
or undefined
message
- an optional message for the error
Example:
function myFun(): Person {
createPerson({ id: 0, name: 'John' });
const entity = findById(0);
return ensuresNonNullish(entity, 'Failed to persist entity');
}
asserts
Clarify that you think that the given condition is impossible to happen.
Throws a AssertionError
if the condition
is false
.
asserts(
condition: boolean,
message?: string
): asserts condition;
condition
- the condition that should be true
message
- an optional message for the error
unreachable
Asserts that a code branch is unreachable. If it is, the compiler will throw a type error.
If this function is reached at runtime, an error will be thrown.
function unreachable(
value: never,
message = 'Reached an unreachable case'
): never;
value
- a value
message
- an optional message for the error
Example:
function myFun(foo: MyEnum): string {
switch (foo) {
case MyEnum.A:
return 'a';
case MyEnum.B:
return 'b';
default:
unreachable(foo);
}
}
error
This function will always throw an error.
It helps keeping code easy to read and come in handy when assigning values with a ternary operator or the null-safe operators.
function error(message?: string): never;
function error(
errorType: new (...args: any[]) => Error,
message?: string
): never;
errorType
- an error class, defaults to IllegalStateError
message
- an optional message for the error
Example:
function myFun(foo: string | null) {
const bar = foo ?? error(PreconditionError, 'Argument may not be null');
const result = bar.length > 0 ? 'OK' : error('Something went wrong!');
}
isDefined
A type guard, to check that a value is not null
or undefined
.
Make sure to use strictNullChecks
.
function isDefined<T>(value: T): value is NonNullable<T>;
value
- the value to test
Example:
const x: string | null = 'Hello';
if (isDefined(x)) {
x.toLowerCase();
}
Errors
The following error classes are included:
PreconditionError
→ An error thrown, if a precondition for a function or method is not met.
IllegalStateError
→ An error thrown, if an object is an illegal state.
PostconditionError
→ An error thrown, if a function or method could not fulfil a postcondition.
AssertionError
→ An error thrown, if an assertion has failed.