Currently, I am attempting to implement type assertion for the "error-first" pattern.
Within my function, it returns tuples in the format of ['error', null]
or [null, 'non-error']
.
The specific condition I want to check for is error === null
, with TypeScript assuming that the second element is not-null.
To illustrate this further, consider the following example:
type ErrorMessage = string;
type ResultError = [ErrorMessage, null];
type ResultOk<T> = [null, T];
type Result<T> = ResultError | ResultOk<T>;
interface I {
x: number;
}
function f(): Result<I> {
if (Math.random() > 0.5) {
return [null, {x: 1}];
} else {
return ['my-error', null];
}
}
const [error1, result1]: Result<I> = f();
// Current approach, manually checking if result1 is not null...
if (result1 !== null) {
console.log(result1.x);
}
// Desiring a different method where only error being null is checked,
// and result1 is automatically assumed as type I
if (error1 === null) {
console.log(result1.x); // TS2531: Object is possibly 'null' <<=====
}