Skip to content

Commit

Permalink
Polish: autobind decode method
Browse files Browse the repository at this point in the history
  • Loading branch information
gcanti committed Mar 26, 2019
1 parent 4964b31 commit 97907c7
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 3 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
**Note**: Gaps between patch versions are faulty/broken releases. **Note**: A feature tagged as Experimental is in a
high state of flux, you're at risk of it changing without notice.

# 1.8.4

- **Polish**
- autobind `decode` method (@gcanti)

# 1.8.3

- **Polish**
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "io-ts",
"version": "1.8.3",
"version": "1.8.4",
"description": "TypeScript compatible runtime type system for IO validation",
"files": [
"lib"
Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ export class Type<A, O = A, I = unknown> implements Decoder<I, A>, Encoder<A, O>
readonly validate: Validate<I, A>,
/** converts a value of type A to a value of type O */
readonly encode: Encode<A, O>
) {}
) {
this.decode = this.decode.bind(this)
}

pipe<B, IB, A extends IB, OB extends A>(
this: Type<A, O, I>,
Expand Down
24 changes: 23 additions & 1 deletion test/TypeClass.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as assert from 'assert'
import * as t from '../src/index'
import { assertSuccess, assertFailure } from './helpers'
import { right } from 'fp-ts/lib/Either'
import { right, Either } from 'fp-ts/lib/Either'

const BAA = new t.Type<number, string, string>(
'BAA',
Expand All @@ -19,6 +19,28 @@ const BAI = t.string.pipe(
)

describe('Type', () => {
it('should auto bind decode', () => {
function clone<C extends t.Any>(t: C): C {
const r = Object.create(Object.getPrototypeOf(t))
;(Object as any).assign(r, t)
return r
}

const T = t.string
const decode = <L, A>(f: (u: unknown) => Either<L, A>, u: unknown): boolean => f(u).isRight()
assert.strictEqual(decode(T.decode, 'a'), true)
assert.strictEqual(decode(clone(T).decode, 'a'), true)
type A = {
a: A | null
}
const A: t.Type<A> = t.recursion('A', () =>
t.type({
a: t.union([A, t.null])
})
)
assert.strictEqual(decode(clone(A).decode, { a: { a: null } }), true)
})

describe('pipe', () => {
it('should assign a default name', () => {
const AOI = t.string
Expand Down

0 comments on commit 97907c7

Please sign in to comment.