Skip to content

Commit

Permalink
Update constant docs and types
Browse files Browse the repository at this point in the history
  • Loading branch information
Elias Mulhall committed Aug 20, 2018
1 parent c4bdce7 commit 80de1f0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/decoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ export class Decoder<A> {
* | constant(true) | Decoder<true> |
* | constant(false) | Decoder<false> |
* | constant(null) | Decoder<null> |
* | constant(undefined) | Decoder<undefined> |
* | constant('alaska') | Decoder<string> |
* | constant<'alaska'>('alaska') | Decoder<'alaska'> |
* | constant(50) | Decoder<number> |
Expand Down Expand Up @@ -474,18 +475,18 @@ export class Decoder<A> {
* ```
*
* Note that the `decoder` is ran on the value found at the last key in the
* path, even if the last key is not found. This allows the `optional`
* decoder to succeed when appropriate.
* path, even if the last key is not found. This allows the value to be
* `undefined` when appropriate.
* ```
* const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
* const decoder = valueAt(['a', 'b', 'c'], union(string(), constant(undefined)));
*
* optionalDecoder.run({a: {b: {c: 'surprise!'}}})
* decoder.run({a: {b: {c: 'surprise!'}}})
* // => {ok: true, result: 'surprise!'}
*
* optionalDecoder.run({a: {b: 'cats'}})
* decoder.run({a: {b: 'cats'}})
* // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
*
* optionalDecoder.run({a: {b: {z: 1}}})
* decoder.run({a: {b: {z: 1}}})
* // => {ok: true, result: undefined}
* ```
*/
Expand Down
16 changes: 16 additions & 0 deletions test/json-decode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,22 @@ describe('constant', () => {
expect(decoder.run({x: null})).toEqual({ok: true, result: {x: null}});
});

it('can decode undefined', () => {
interface UndefinedValue {
a: string;
b: undefined;
}
const decoder = object<UndefinedValue>({a: string(), b: constant(undefined)});

const run1 = decoder.run({a: 'qwerty', b: undefined});
expect(run1).toEqual({ok: true, result: {a: 'qwerty', b: undefined}});
expect(Result.map(Object.keys, run1)).toEqual({ok: true, result: ['a', 'b']});

const run2 = decoder.run({a: 'asdfgh'});
expect(run2).toEqual({ok: true, result: {a: 'asdfgh', b: undefined}});
expect(Result.map(Object.keys, run2)).toEqual({ok: true, result: ['a', 'b']});
});

it('can decode a constant array', () => {
type A = [1, 2, 3];
const decoder: Decoder<A> = constant<A>([1, 2, 3]);
Expand Down

0 comments on commit 80de1f0

Please sign in to comment.