Design by contract with TypeScript.
npm i ts-code-contracts
Requires TypeScript^3.7
You can now import the following functions from 'ts-code-contracts'
:
requires
for preconditionschecks
for invariantsensures
for postconditionsasserts
for impossible eventsunreachable
for unreachable code brancheserror
to make code more conciseisDefined
type guard
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.
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 betrue
message
- an optional message for the error
Example:
function myFun(name: string) {
requires(name.length > 10, 'Name must be longer than 10 chars');
}
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 benull
orundefined
message
- an optional message for the error
Example:
function myFun(name: string | null) {
const nameNonNull = requiresNonNullish(name, 'Name must be defined');
nameNonNull.toUpperCase(); // no compiler error!
}
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 betrue
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;
}
}
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 benull
orundefined
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(); // no compiler error!
}
}
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 betrue
message
- an optional message for the error
Example:
function myFun() {
createPerson({ id: 0, name: 'John' });
const entity = findById(0); // returns null if not present
return ensures(isDefined(entity), 'Failed to persist entity');
}
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 benull
orundefined
message
- an optional message for the error
Example:
function myFun(): Person {
createPerson({ id: 0, name: 'John' });
const entity = findById(0); // returns null if not present
return ensuresNonNullish(entity, 'Failed to persist entity');
}
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 betrue
message
- an optional message for the error
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 valuemessage
- an optional message for the error
Example:
function myFun(foo: MyEnum): string {
switch (foo) {
case MyEnum.A:
return 'a';
case MyEnum.B:
return 'b';
// no compiler error if MyEnum only has A and B
default:
unreachable(foo);
}
}
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 toIllegalStateError
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!');
}
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(); // no compiler error!
}
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.