Skip to content

Commit

Permalink
fix(or): fixing typing for or
Browse files Browse the repository at this point in the history
  • Loading branch information
mirek committed Oct 5, 2023
1 parent 5aa0890 commit e881132
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 6 deletions.
10 changes: 10 additions & 0 deletions src/null-or.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as $ from './index.js'

test('simple', () => {
const union = $.or($.string, $.number)
const assert = $.nullOr(union)
expect(assert(null)).toEqual(null)
expect(assert(1)).toEqual(1)
expect(assert('foo')).toEqual('foo')
expect(() => assert(true)).toThrow('')
})
3 changes: 2 additions & 1 deletion src/or.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as $ from './index.js'

test('or', () => {
const r = $.or($.number, $.string)(JSON.parse('"foo"'))
const assert = $.or($.number, $.string)
const r = assert(JSON.parse('"foo"'))
expect(r).toEqual('foo')
})
10 changes: 5 additions & 5 deletions src/or.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { Assert } from './prelude.js'
import type { Assert, Asserted } from './prelude.js'
import { inspect } from 'util'

const or: <T extends Assert<unknown>[]>(...as: T) => T[number] =
(...as) =>
value => {
const or =
<As extends Assert<unknown>[]>(...as: As) =>
(value: unknown) => {
for (const a of as) {
try {
return a(value)
return a(value) as Asserted<As[number]>
} catch (err) {
continue
}
Expand Down
3 changes: 3 additions & 0 deletions src/prelude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,6 @@ export type OptionalIfUndefinedOnly<T> = {

export type OptionalIfUndefined<T> =
Omit<T, keyof OptionalIfUndefinedOnly<T>> & OptionalIfUndefinedOnly<T>

export type IntersectionOfUnion<T> =
(T extends unknown ? (_: T) => unknown : never) extends (_: infer R) => unknown ? R : never

0 comments on commit e881132

Please sign in to comment.