Skip to content

Commit

Permalink
feat: adding a very powerful type call AnyKey.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Sander Hoogendoorn committed Aug 22, 2024
1 parent 2c8312d commit 57f28b8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/easy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export * from './sql/Table';
export * from './sql/TableGateway';
export * from './sql/Update';

export * from './types/AnyKey';
export * from './types/Array';
export * from './types/Builder';
export * from './types/Cache';
Expand Down
3 changes: 3 additions & 0 deletions packages/easy/src/types/AnyKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type AnyKey<T> = {
[Key in keyof T & (string | number)]: T[Key] extends object ? `${Key}` | `${Key}.${AnyKey<T[Key]>}` : `${Key}`;
}[keyof T & (string | number)];
24 changes: 24 additions & 0 deletions packages/easy/test/types/AnyKey.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { AnyKey, traverse } from '../../src';

class Test<T> {
constructor(public readonly value: T) {}

toValue = (key: AnyKey<T>) => traverse(this.value, key);
}

describe('AnyKey', () => {
const data = {
id: 42,
name: { first: 'Jan', last: 'Jansen', address: { city: 'Amsterdam', country: 'NL' } },
paid: { currency: 'EUR', cents: 3000 },
};

test('toValue', () => {
const t = new Test(data);
expect(t.toValue('id')).toBe(42);
expect(t.toValue('name.last')).toBe('Jansen');
expect(t.toValue('name.first')).toBe('Jan');
expect(t.toValue('paid.cents')).toBe(3000);
expect(t.toValue('name.address.city')).toBe('Amsterdam');
});
});

0 comments on commit 57f28b8

Please sign in to comment.