-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
branded.test.ts
63 lines (50 loc) · 1.79 KB
/
branded.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// @ts-ignore TS6133
import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts";
const test = Deno.test;
import { util } from "../helpers/util.ts";
import * as z from "../index.ts";
test("branded types", () => {
const mySchema = z
.object({
name: z.string(),
})
.brand<"superschema">();
// simple branding
type MySchema = z.infer<typeof mySchema>;
util.assertEqual<
MySchema,
{ name: string } & { [z.BRAND]: { superschema: true } }
>(true);
const doStuff = (arg: MySchema) => arg;
doStuff(mySchema.parse({ name: "hello there" }));
// inheritance
const extendedSchema = mySchema.brand<"subschema">();
type ExtendedSchema = z.infer<typeof extendedSchema>;
util.assertEqual<
ExtendedSchema,
{ name: string } & z.BRAND<"superschema"> & z.BRAND<"subschema">
>(true);
doStuff(extendedSchema.parse({ name: "hello again" }));
// number branding
const numberSchema = z.number().brand<42>();
type NumberSchema = z.infer<typeof numberSchema>;
util.assertEqual<NumberSchema, number & { [z.BRAND]: { 42: true } }>(true);
// symbol branding
const MyBrand: unique symbol = Symbol("hello");
type MyBrand = typeof MyBrand;
const symbolBrand = z.number().brand<"sup">().brand<typeof MyBrand>();
type SymbolBrand = z.infer<typeof symbolBrand>;
// number & { [z.BRAND]: { sup: true, [MyBrand]: true } }
util.assertEqual<SymbolBrand, number & z.BRAND<"sup"> & z.BRAND<MyBrand>>(
true
);
// keeping brands out of input types
const age = z.number().brand<"age">();
type Age = z.infer<typeof age>;
type AgeInput = z.input<typeof age>;
util.assertEqual<AgeInput, Age>(false);
util.assertEqual<number, AgeInput>(true);
util.assertEqual<number & z.BRAND<"age">, Age>(true);
// @ts-expect-error
doStuff({ name: "hello there!" });
});