Skip to content

Commit

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

* update createDefaultCodec to correctly handle object types

* bump package version
  • Loading branch information
abrantesarthur authored Jan 19, 2025
1 parent b1029f7 commit cac2f41
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.2",
"version": "1.8.3",
"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 @@ -116,6 +116,11 @@ export const createDefaultCodec = <C extends t.Mixed>(
return codec.value as t.TypeOf<C>;
}

// The default of an object type is an empty object
if (codec instanceof t.ObjectType) {
return {} 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 @@ -38,6 +38,12 @@ describe('buildDefaultCodec', () => {
expect(defaultCodec).to.equal('A');
});

it('should correctly build a default codec for an object', () => {
const codec = t.object;
const defaultCodec = createDefaultCodec(codec);
expect(defaultCodec).to.deep.equal({});
});

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 cac2f41

Please sign in to comment.