diff --git a/src/index.spec.ts b/src/index.spec.ts index 9c3e615..aeec7b3 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -366,3 +366,15 @@ describe('separate with union value', () => { Foo.union({ status: 'b', payload: 'something' }); }); }); + +describe('record tags', () => { + const LightBulb = unionize({ + ON: ofType<{ dimLevel: number }>(), + OFF: ofType<{}>(), + }); + + it('should allow to access the tags', () => { + expect(LightBulb.tags.ON).toBe('ON'); + expect(LightBulb.tags.OFF).toBe('OFF'); + }); +}); diff --git a/src/index.ts b/src/index.ts index 9000219..c88d949 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ export interface UnionTypes { export interface UnionExtensions { is: Predicates; as: Casts; + tags: TagRecord; match: Match; transform: Transform; } @@ -57,6 +58,8 @@ export interface Transform { (variant: Union, cases: TransformCases): Union; } +export type TagRecord = { [T in keyof Record]: T }; + export type MultiValueVariants, TagProp extends string> = { [T in keyof Record]: Record[T] extends { [_ in TagProp]: T } // does record already has tag with correct value? ? Record[T] // yes: return as is @@ -144,10 +147,16 @@ export function unionize(record: Record, config?: { value?: string; tag? }); } + const tags = {} as TagRecord; + for (const tag in record) { + tags[tag] = tag; + } + return Object.assign( { is, as, + tags, match, transform, _Record: record,