0.0.2 Type System Improvements
Overview
This release changes a lot with how Typescript's type system interacts with the already existing functions. Much work has been done to make sure that Typescript knows when and what errors exist on a particular value and allow for proper narrowing with isErr
. This also introduces a new concept of causality. Every error has a cause
property on it that identifies it as an error of a particular type. This is compatible with numbers
and strings
, which makes using enums
possible to both identify and reuse identifying causes for errors in a function.
Changelog:
-
Linting Rule Change: The updated code now includes a directive to ignore the "no-explicit-any" linting rule for the entire file.
-
Type Changes:
- The
Result
type now includesCustomError
as a possible error type. - The
CustomError
type has been expanded to include a cause property of typeC
which extendsValidCause
, and amessage
property of typeM
which extendsstring
.
- The
-
Function Changes:
- The
addMsg
function now checks if the error message length is less than or equal to 0 before assigning the message. - The
Err
function now accepts acause
argument and an optionalmessage
argument, and returns aCustomError
with these properties. - The
Try
function now accepts an optionalcause
argument and returns aCustomError
with this cause if an error is thrown. - The
isErr
function now accepts an optionalcause
argument and checks if the value'scause
matches this cause when determining if the value is an error. - The
Ok
function now returnsExclude<T, Error>
instead ofT
, excludingError
from the possible return types.
- The
-
New Types and Functions:
- A new type
ValidCause
has been introduced, which can be a string or number. - A new type
ExtractCause
has been introduced, which extracts the cause property from a given type. - A new function
addMsg
has been introduced, which adds a message to an error and returns aCustomError
.
- A new type
Example
enum DatabaseErrorCause {
NotFound = 'NOT_FOUND',
ConnectionError = 'CONNECTION_ERROR',
UnexpectedError = 'UNEXPECTED_ERROR',
}
type DatabaseError = CustomError<DatabaseErrorCause, string>;
function fetchUserData(id: string): Result<UserData, DatabaseError> {
// ... fetch user data from database
// If an error occurs, return a CustomError with a specific cause
if (error) {
return Err(DatabaseErrorCause.NotFound, `User with id ${id} not found.`);
}
// If everything is fine, return the user data
return userData;
}
const result = fetchUserData('123');
const errorMessages = {
[DatabaseErrorCause.NotFound]: 'User not found. Please check the id.',
[DatabaseErrorCause.ConnectionError]: 'Could not connect to the database. Please check your connection.',
[DatabaseErrorCause.UnexpectedError]: 'An unexpected error occurred.',
};
if (isErr(result)) {
console.log(errorMessages[result.cause]);
} else {
console.log('User data:', result);
}
Full Changelog: 0.0.1...0.0.2