Skip to content

Commit

Permalink
Merge pull request #180 from gvergnaud/gvergnaud/fix-branded-types
Browse files Browse the repository at this point in the history
🐛 fix: Accept branded primitive types as patterns
  • Loading branch information
gvergnaud authored Jul 19, 2023
2 parents 369e88c + 3c79646 commit 37f4a1b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/types/Pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ type KnownPatternInternal<
a,
objs = Exclude<a, Primitives | Map<any, any> | Set<any> | readonly any[]>,
arrays = Extract<a, readonly any[]>,
primitives = Exclude<a, object>
primitives = Extract<a, Primitives>
> =
| primitives
| PatternMatcher<a>
Expand Down
34 changes: 34 additions & 0 deletions tests/branded-nominal-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,38 @@ describe('Branded strings', () => {
.otherwise(() => 'nope')
).toEqual('Match: value');
});

it('issue #167', () => {
const tag: unique symbol = Symbol();
type Tagged<Token> = { readonly [tag]: Token };
type Opaque<Type, Token = unknown> = Type & Tagged<Token>;

const opaqueString = (Math.random() > 0.5 ? 'A' : 'B') as Opaque<'A' | 'B'>;

match(opaqueString)
.with('A' as Opaque<'A'>, () => 1)
.with('B' as Opaque<'B'>, () => 2)
.exhaustive();
});

it('issue #178', () => {
const symbol: unique symbol = Symbol();

interface Branded<key extends string> {
[symbol]: { [k in key]: true };
}

type Brand<a, key extends string> = a & Branded<key>;
type BrandId = Brand<number, 'BrandId'>;

const a: number = 1;
const b: BrandId = 1 as BrandId;

expect(
match({ a, b })
.with({ a, b }, () => '1')
.with({ a: P.number, b: P.number }, () => '2')
.exhaustive()
).toEqual('1');
});
});

0 comments on commit 37f4a1b

Please sign in to comment.