Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface UnionTypes<Record, TaggedRecord> {
export interface UnionExtensions<Record, TaggedRecord> {
is: Predicates<TaggedRecord>;
as: Casts<Record, TaggedRecord[keyof TaggedRecord]>;
tags: TagRecord<Record>;
match: Match<Record, TaggedRecord[keyof TaggedRecord]>;
transform: Transform<Record, TaggedRecord[keyof TaggedRecord]>;
}
Expand Down Expand Up @@ -57,6 +58,8 @@ export interface Transform<Record, Union> {
(variant: Union, cases: TransformCases<Record, Union>): Union;
}

export type TagRecord<Record> = { [T in keyof Record]: T };

export type MultiValueVariants<Record extends MultiValueRec<TagProp>, 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
Expand Down Expand Up @@ -144,10 +147,16 @@ export function unionize<Record>(record: Record, config?: { value?: string; tag?
});
}

const tags = {} as TagRecord<Record>;
for (const tag in record) {
tags[tag] = tag;
}

return Object.assign(
{
is,
as,
tags,
match,
transform,
_Record: record,
Expand Down