Superposition Motivation
Superposition is a Try
package for TS that can deal with Promise.
Many languages have Exception
function. When exceptions are thrown, that method immediately shut the process and until
the exception is caught, the shut-process goes up to the callees.
Error
is called for Exception
in JavaScript, TypeScript, but they are equivalent.
We can catch errors by using try-catch
syntax. put the methods that may throw errors in try
and if errors are
thrown, catch
can catch them.
try {
method();
}
catch (err: unknown) {
// ...
}
TypeScript can catch errors, but these errors must be any, unknown
in TypeScript because JavaScript can throw whatever
you want, even if it is string, other primitive types, or something else.
Exceptions in Java can be thrown when the class implements Throwable
, and it also supports thrown
clause that
describes the methods may throw such Exceptions to the callee.
TypeScript does not support throws
. It cannot check errors. The caller has to investigate and know what is going to be
thrown when they call methods in advance.
Try
enables us to avoid this problem. Try
describes that might succeed, or might fail.
In general, Try
is an abstract class, and it has 2 concrete classes, one is Success
that describes that has an
expected value, another is Failure
that describes that has an unexpected value (mainly it would be an exception)
. Try
can force users to consider whether the instance is an expected value or no.
To build Try
, you can easily achieve by using Union types
, and `Discriminated unions.
type Success<T> = Readonly<{
success: true;
value: T;
}>;
type Failure = Readonly<{
success: false;
error: unknown;
}>;
type Try<T> = Success<T> | Failure;
We can immediately find that is Success<T>, Failure
only if we check tried.success
.
const tried: Try<UserID> = createUser(user);
if (tried.success) {
// This tried is Success<UserID>
}
else {
// This tried is Failure
}
This is an interface, this retains either result, succeeded one or failed one, and also describes the status
for Superposition
.
4 classes implement Schrodinger
and each of them means
-
Alive<A, D>
- This means fulfilled, and retains the succeeded instance as expected
-
Dead<A, D>
- This means recoverable rejected, and retains no errors. Errors must be one or more of the instances of the generic D
-
Contradiction<A, D>
- This means rejected, and retains
unknown
value- This is equivalent to
rejected Promise
but this is not recoverable
- This is equivalent to
- This means rejected, and retains
-
Still<A, D>
- This means pending, the result is not ready
Alive, Dead, Contradiction
are called SETTLED, that means, when it would be once, would never change to others.
This is an interface that is alternative for resolve, reject
in new Promise()
. This
can accept(), decline(), and throw()
.
When accepted one, the result would be Alive
, declined once, the result would be Dead
, thrown once, the result would
be Contradiction
.`