Skip to content

Commit

Permalink
feat(metadata): expose OmitMetadata generic
Browse files Browse the repository at this point in the history
  • Loading branch information
uladkasach committed Jun 11, 2024
1 parent d694c2c commit 20bfea9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/checks/hasMetadata.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { hasMetadata } from '..';
import { HasMetadata } from './hasMetadata';
import { HasMetadata, OmitMetadata } from './hasMetadata';

describe('HasMetadata', () => {
it('should enable accessing an optional metadata property of a type', () => {
Expand All @@ -9,6 +9,23 @@ describe('HasMetadata', () => {
});
});

describe('OmitMetadata', () => {
it('should prevent specifying a metadata property of a type', () => {
type FlowerPot = { id?: number; age: number };

// @ts-expect-error - should not be able to set id
const pot: OmitMetadata<FlowerPot> = { id: 123, age: 72 };

Check warning on line 17 in src/checks/hasMetadata.test.ts

View workflow job for this annotation

GitHub Actions / suite / test-lint

'pot' is assigned a value but never used
});
it('should prevent accessing a metadata property of a type', () => {
type FlowerPot = { id?: number; age: number };

const pot: OmitMetadata<FlowerPot> = { age: 72 };

// @ts-expect-error - should not be able to get id
expect(pot.id).not.toBeDefined();
});
});

describe('hasMetadata', () => {
it('should enable accessing an optional metadata property of a type', () => {
type FlowerPot = { id?: number; age: number };
Expand Down
23 changes: 23 additions & 0 deletions src/checks/hasMetadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const typicalMetadataKeys = [
'deletedAt',
'effectiveAt',
] as const;

/**
* these are the keys most commonly used metadata keys
*/
Expand Down Expand Up @@ -44,6 +45,28 @@ export type HasMetadata<
>
>;

/**
* asserts that any optional metadata keys of the object will now be omitted
*
* by default, the following keys are considered to be metadata:
* - `id`
* - `uuid`
* - `createdAt`
* - `updatedAt`
* - `deletedAt`
* - `effectiveAt`
*/
export type OmitMetadata<
T extends Record<string, any>,
MetadataKeys = TypicalMetadataKeys,
> =
// omit all keys
Omit<
T,
keyof T & // that are on the object
MetadataKeys // and are metadata keys
>;

/**
* for an object of type T, asserts that the object HasMetadata<T, K> for all listed metadata keys K
*
Expand Down

0 comments on commit 20bfea9

Please sign in to comment.