Skip to content

Commit

Permalink
Create an asTransientProps helper
Browse files Browse the repository at this point in the history
  • Loading branch information
jessepinho committed Jul 11, 2024
1 parent 69be946 commit acc6a98
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/ui/src/utils/asTransientProps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest';
import { asTransientProps } from './asTransientProps';

describe('asTransientProps()', () => {
it('converts all properties to have a `$` prefix', () => {
const props = {
size: 'lg',
color: 'red',
};

const expected = {
$size: 'lg',
$color: 'red',
};

expect(asTransientProps(props)).toEqual(expected);
});
});
17 changes: 17 additions & 0 deletions packages/ui/src/utils/asTransientProps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Thanks to https://stackoverflow.com/a/65278278/974981 for the prefixer
// utility types
type Prefix<K extends string, T extends string> = `${K}${T}`;

type Prefixer<K, T extends string> = {
[P in keyof K as Prefix<T, string & P>]: K[P];
};

export type AsTransientProps<T extends Record<string, unknown>> = Prefixer<T, '$'>;

export const asTransientProps = <T extends Record<string, unknown>>(
props: T,
): AsTransientProps<T> =>
Object.entries(props).reduce<Partial<AsTransientProps<T>>>((prev, curr) => {
const [key, value] = curr;
return { ...prev, [`$${key}`]: value };
}, {}) as unknown as AsTransientProps<T>;

0 comments on commit acc6a98

Please sign in to comment.