Skip to content

Commit f4b47e7

Browse files
committed
Add result type
1 parent 4e14537 commit f4b47e7

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/util.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1292,3 +1292,33 @@ export function joinAtMost(
12921292

12931293
return array.join(separator);
12941294
}
1295+
1296+
type Success<T> = Result<T, never>;
1297+
type Failure<E> = Result<never, E>;
1298+
1299+
export class Result<T, E> {
1300+
private constructor(
1301+
private readonly _ok: boolean,
1302+
public readonly value: T | E,
1303+
) {}
1304+
1305+
static ok<T>(value: T): Success<T> {
1306+
return new Result(true, value) as Success<T>;
1307+
}
1308+
1309+
static error<E>(error: E): Failure<E> {
1310+
return new Result(false, error) as Failure<E>;
1311+
}
1312+
1313+
isOk(): this is Success<T> {
1314+
return this._ok;
1315+
}
1316+
1317+
isError(): this is Failure<E> {
1318+
return !this._ok;
1319+
}
1320+
1321+
orElse(defaultValue: T): T {
1322+
return this._ok ? (this.value as T) : defaultValue;
1323+
}
1324+
}

0 commit comments

Comments
 (0)