Skip to content

Commit

Permalink
Add Result type guards (#8835)
Browse files Browse the repository at this point in the history
### Description

Adds type guards for the Result type
  • Loading branch information
nambrot authored Oct 25, 2021
1 parent c098fd7 commit 23a3529
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/sdk/base/src/result.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Err, isOk, Ok, Result } from '.'

// These tests are just to check the typescript compiler
describe('discriminated collection functions', () => {
const trueValue = Ok(true)
const falseValue = Err(new Error())
const collection: Array<Result<boolean, Error>> = [trueValue, falseValue]

it('can filter to the true value', () => {
const ok = collection.filter(isOk)
expect(ok.map((_) => _.result)).toEqual([true])
})

it('can find in collection', () => {
const ok = collection.find(isOk)
if (ok) {
expect(ok.result).toEqual(true)
}
})
})
12 changes: 12 additions & 0 deletions packages/sdk/base/src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,15 @@ export function parseJsonAsResult(data: string) {
return Err(new JSONParseError(error))
}
}

export function isOk<TResult, TError extends Error>(
result: Result<TResult, TError>
): result is OkResult<TResult> {
return result.ok
}

export function isErr<TResult, TError extends Error>(
result: Result<TResult, TError>
): result is ErrorResult<TError> {
return !result.ok
}

0 comments on commit 23a3529

Please sign in to comment.