From acc6a98c6dceb9b44ecb31fe1e2c65591b3d16a1 Mon Sep 17 00:00:00 2001 From: Jesse Pinho Date: Thu, 11 Jul 2024 00:38:00 -0700 Subject: [PATCH] Create an asTransientProps helper --- packages/ui/src/utils/asTransientProps.test.ts | 18 ++++++++++++++++++ packages/ui/src/utils/asTransientProps.ts | 17 +++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 packages/ui/src/utils/asTransientProps.test.ts create mode 100644 packages/ui/src/utils/asTransientProps.ts diff --git a/packages/ui/src/utils/asTransientProps.test.ts b/packages/ui/src/utils/asTransientProps.test.ts new file mode 100644 index 000000000..1245812c1 --- /dev/null +++ b/packages/ui/src/utils/asTransientProps.test.ts @@ -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); + }); +}); diff --git a/packages/ui/src/utils/asTransientProps.ts b/packages/ui/src/utils/asTransientProps.ts new file mode 100644 index 000000000..27d0a55aa --- /dev/null +++ b/packages/ui/src/utils/asTransientProps.ts @@ -0,0 +1,17 @@ +// Thanks to https://stackoverflow.com/a/65278278/974981 for the prefixer +// utility types +type Prefix = `${K}${T}`; + +type Prefixer = { + [P in keyof K as Prefix]: K[P]; +}; + +export type AsTransientProps> = Prefixer; + +export const asTransientProps = >( + props: T, +): AsTransientProps => + Object.entries(props).reduce>>((prev, curr) => { + const [key, value] = curr; + return { ...prev, [`$${key}`]: value }; + }, {}) as unknown as AsTransientProps;