Skip to content

Commit

Permalink
feature: Object omit
Browse files Browse the repository at this point in the history
  • Loading branch information
vbudovski committed Dec 25, 2024
1 parent 1cc076e commit 4a193d9
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,23 @@ p.object({
});
*/
```

### `omit`

Analogous to TypeScript's built-in `Omit` utility type. Creates a schema that contains all except the selected keys.

```typescript
import * as p from '@vbudovski/paseri';

const schema = p.object({
foo: p.string(),
bar: p.number(),
});
const schemaOmitted = schema.omit('foo');
/*
The resulting schema will be:
p.object({
bar: p.number(),
});
*/
```
14 changes: 14 additions & 0 deletions paseri-lib/src/schemas/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,3 +393,17 @@ test('Pick', () => {
expect(result.ok).toBeTruthy();
}
});

test('Omit', () => {
const schema = p.object({ foo: p.string(), bar: p.number() });
const schemaOmitted = schema.omit('foo');

const data = { bar: 123 };
const result = schemaOmitted.safeParse(data);
if (result.ok) {
expectTypeOf(result.value).toEqualTypeOf<{ bar: number }>;
expect(result.value).toEqual(data);
} else {
expect(result.ok).toBeTruthy();
}
});
12 changes: 11 additions & 1 deletion paseri-lib/src/schemas/object.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Merge, NonEmptyObject, TupleToUnion } from 'type-fest';
import type { IsEqual, Merge, NonEmptyObject, TupleToUnion } from 'type-fest';
import type { Infer } from '../infer.ts';
import { type LeafNode, type TreeNode, issueCodes } from '../issue.ts';
import { addIssue } from '../issue.ts';
Expand Down Expand Up @@ -184,6 +184,16 @@ class ObjectSchema<ShapeType extends ValidShapeType<ShapeType>> extends Schema<I
Object.fromEntries(this._shape.entries().filter(([key]) => keys.includes(key as keyof ShapeType))),
);
}
omit<Keys extends [keyof ShapeType, ...(keyof ShapeType)[]]>(
// Ensure at least one key remains in schema.
...keys: IsEqual<TupleToUnion<Keys>, keyof ShapeType> extends true ? never : Keys
// @ts-expect-error FIXME: How do we get the shape validation to play nicely with Omit?
): ObjectSchema<Omit<ShapeType, TupleToUnion<Keys>>> {
// @ts-expect-error FIXME: How do we get the shape validation to play nicely with Omit?
return new ObjectSchema<Omit<ShapeType, TupleToUnion<Keys>>>(
Object.fromEntries(this._shape.entries().filter(([key]) => !keys.includes(key as keyof ShapeType))),
);
}
}

function object<ShapeType extends ValidShapeType<ShapeType>>(
Expand Down

0 comments on commit 4a193d9

Please sign in to comment.