Skip to content

Commit

Permalink
update createDefaultCodec to handle literal types correctly (#33)
Browse files Browse the repository at this point in the history
* update createDefaultCodec to handle literal types correctly

* lint

* lint

* lint
  • Loading branch information
abrantesarthur authored Jan 19, 2025
1 parent d7e23a3 commit b1029f7
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"author": "Transcend Inc.",
"name": "@transcend-io/type-utils",
"description": "Small package containing useful typescript utilities.",
"version": "1.8.1",
"version": "1.8.2",
"homepage": "https://github.com/transcend-io/type-utils",
"repository": {
"type": "git",
Expand Down
5 changes: 5 additions & 0 deletions src/codecTools/createDefaultCodec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ export const createDefaultCodec = <C extends t.Mixed>(
) as t.TypeOf<C>;
}

// The default of a literal type is its value
if (codec instanceof t.LiteralType) {
return codec.value as t.TypeOf<C>;
}

// Handle primitive and common types
switch (codec.name) {
case 'string':
Expand Down
6 changes: 6 additions & 0 deletions src/tests/createDefaultCodec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ describe('buildDefaultCodec', () => {
expect(result).to.equal('');
});

it('should correctly build a default codec for a union of literals', () => {
const codec = t.union([t.literal('A'), t.literal('B')]);
const defaultCodec = createDefaultCodec(codec);
expect(defaultCodec).to.equal('A');
});

it('should correctly build a default codec for a union with null', () => {
const result = createDefaultCodec(t.union([t.string, t.null]));
// should default to null if the union contains null
Expand Down

0 comments on commit b1029f7

Please sign in to comment.