-
Notifications
You must be signed in to change notification settings - Fork 1
/
renaming-union-field.test.ts
50 lines (44 loc) · 1.42 KB
/
renaming-union-field.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
import { expectType, TypeEqual } from "ts-expect";
import { expect, test } from "vitest";
import { Infer, InferEncoded, number, tag, taggedUnion } from "../index.js";
test("using different tags in JSON and in TypeScript", () => {
// Here’s how to use different keys and values in JSON and TypeScript.
// For example, `"type": "circle"` → `tag: "Circle"`.
const shapeCodec = taggedUnion("tag", [
{
tag: tag("Circle", { renameTagFrom: "circle", renameFieldFrom: "type" }),
radius: number,
},
{
tag: tag("Square", { renameTagFrom: "square", renameFieldFrom: "type" }),
size: number,
},
]);
type InferredType = Infer<typeof shapeCodec>;
type ExpectedType =
| { tag: "Circle"; radius: number }
| { tag: "Square"; size: number };
expectType<TypeEqual<InferredType, ExpectedType>>(true);
type InferredEncodedType = InferEncoded<typeof shapeCodec>;
type ExpectedEncodedType =
| { type: "circle"; radius: number }
| { type: "square"; size: number };
expectType<TypeEqual<InferredEncodedType, ExpectedEncodedType>>(true);
expect(shapeCodec.decoder({ type: "circle", radius: 5 }))
.toMatchInlineSnapshot(`
{
"tag": "Valid",
"value": {
"radius": 5,
"tag": "Circle",
},
}
`);
expect(shapeCodec.encoder({ tag: "Circle", radius: 5 }))
.toMatchInlineSnapshot(`
{
"radius": 5,
"type": "circle",
}
`);
});