Skip to content

Commit 1d84380

Browse files
author
Elias Mulhall
committed
Update constant docs and types
1 parent 5152ad2 commit 1d84380

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

src/decoder.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ export class Decoder<A> {
217217
* | constant(true) | Decoder<true> |
218218
* | constant(false) | Decoder<false> |
219219
* | constant(null) | Decoder<null> |
220+
* | constant(undefined) | Decoder<undefined> |
220221
* | constant('alaska') | Decoder<string> |
221222
* | constant<'alaska'>('alaska') | Decoder<'alaska'> |
222223
* | constant(50) | Decoder<number> |
@@ -472,18 +473,18 @@ export class Decoder<A> {
472473
* ```
473474
*
474475
* Note that the `decoder` is ran on the value found at the last key in the
475-
* path, even if the last key is not found. This allows the `optional`
476-
* decoder to succeed when appropriate.
476+
* path, even if the last key is not found. This allows the value to be
477+
* `undefined` when appropriate.
477478
* ```
478-
* const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
479+
* const decoder = valueAt(['a', 'b', 'c'], union(string(), constant(undefined)));
479480
*
480-
* optionalDecoder.run({a: {b: {c: 'surprise!'}}})
481+
* decoder.run({a: {b: {c: 'surprise!'}}})
481482
* // => {ok: true, result: 'surprise!'}
482483
*
483-
* optionalDecoder.run({a: {b: 'cats'}})
484+
* decoder.run({a: {b: 'cats'}})
484485
* // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
485486
*
486-
* optionalDecoder.run({a: {b: {z: 1}}})
487+
* decoder.run({a: {b: {z: 1}}})
487488
* // => {ok: true, result: undefined}
488489
* ```
489490
*/

test/json-decode.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,22 @@ describe('constant', () => {
147147
expect(decoder.run({x: null})).toEqual({ok: true, result: {x: null}});
148148
});
149149

150+
it('can decode undefined', () => {
151+
interface UndefinedValue {
152+
a: string;
153+
b: undefined;
154+
}
155+
const decoder = object<UndefinedValue>({a: string(), b: constant(undefined)});
156+
157+
const run1 = decoder.run({a: 'qwerty', b: undefined});
158+
expect(run1).toEqual({ok: true, result: {a: 'qwerty', b: undefined}});
159+
expect(Result.map(Object.keys, run1)).toEqual({ok: true, result: ['a', 'b']});
160+
161+
const run2 = decoder.run({a: 'asdfgh'});
162+
expect(run2).toEqual({ok: true, result: {a: 'asdfgh', b: undefined}});
163+
expect(Result.map(Object.keys, run2)).toEqual({ok: true, result: ['a', 'b']});
164+
});
165+
150166
it('can decode a constant array', () => {
151167
type A = [1, 2, 3];
152168
const decoder: Decoder<A> = constant<A>([1, 2, 3]);

0 commit comments

Comments
 (0)