Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ if (result.isError()) {

if (result.isOk()) {
console.log(result.getValue());
}
else {
} else {
console.error(result.getError());
}
```
Expand All @@ -47,7 +46,8 @@ else {

| Method | Description |
| --------------------- | -------------------------------------------------------- |
| `Result.ok(value?)` | Creates a successful result, optionally holding a value. |
| `Result.ok()` | Creates a successful `Result<void>`, with no value. |
| `Result.ok(value)` | Creates a successful result, holding a value. |
| `Result.error(error)` | Creates a failed result holding an `Error`. |

### Inspecting a result
Expand All @@ -58,7 +58,6 @@ else {
| `isError()` | `boolean` | `true` if the result is a failure. |
| `getValue()` | `T \| undefined` | The value of a success. `undefined` for a failure. |
| `getError()` | `Error \| undefined` | The error of a failure. `undefined` for a success. |
| | | |

## Notes

Expand Down Expand Up @@ -89,6 +88,25 @@ function parseUrl(input: string): Result<URL> {
}
```

### Results without a value

`Result.ok()` with no argument returns a `Result<void>`. For any other type, pass the value explicitly, even if it is `undefined`:

```ts
function deleteUser(id: string): Result<void> {
db.remove(id);
return Result.ok();
}

function findUser(id: string): Result<User | undefined> {
try {
return Result.ok(db.get(id)); // undefined if there is no such user
} catch (error) {
return Result.error(error instanceof Error ? error : new Error(String(error)));
}
}
```

## Contributing

1. Fork the repository.
Expand Down
11 changes: 11 additions & 0 deletions src/result.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ describe('Result', () => {
test('getError', () => {
expect(result.getError()).toBeUndefined();
});

test('without a value is allowed for Result<void>', () => {
const result: Result<void> = Result.ok();
expect(result.isOk()).toBe(true);
expect(result.getValue()).toBeUndefined();
});

test('without a value is NOT assignable to Result<number>', () => {
// @ts-expect-error: a missing value must not satisfy Result<number>
const result: Result<number> = Result.ok();
});
});

describe('Result.error', () => {
Expand Down
2 changes: 2 additions & 0 deletions src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ class ResultImpl<T> {
this.error = error;
}

static ok(): Result<void>;
static ok<T>(value: T): Result<T>;
static ok<T>(value?: T): Result<T> {
return new ResultImpl<T>(true, value) as Result<T>;
}
Expand Down
Loading