Skip to content
Open
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
35 changes: 35 additions & 0 deletions src/types/result.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, test } from 'vitest';

import type { Result } from './result';

describe('Result', () => {
test('can be initialized with a success value', () => {
const result: Result<string, Error> = {
success: 'foo',
};
expect(result.success).toBe('foo');
expect(result.error).toBeUndefined();
});

test('can be initialized with an error', () => {
const FooErrorType = {
networkError: 0,
decodingError: 1,
} as const;
type FooErrorType = (typeof FooErrorType)[keyof typeof FooErrorType];

class FooError extends Error {
type?: FooErrorType;

constructor(type: FooErrorType) {
super();
this.type = type;
}
}
const result: Result<string, FooError> = {
error: new FooError(FooErrorType.decodingError),
};
expect(result.success).toBeUndefined();
expect(result.error?.type).toBe(FooErrorType.decodingError);
});
});
18 changes: 18 additions & 0 deletions src/types/result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* The Result is a container for a response.
*
* It contains an optional success result which is generic
* and can be anything depending on the context,
* or an Error or subclass of an error.
*
* This allows us to return rich, typed errors instead of
* an untyped Promise rejection.
*
* This is modeled after Swift's Result type:
* https://developer.apple.com/documentation/swift/result
*/
export interface Result<T, E extends Error> {
success?: T;

error?: E;
}
Loading