forked from ianstormtaylor/superstruct
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesting-values.ts
More file actions
36 lines (30 loc) · 787 Bytes
/
testing-values.ts
File metadata and controls
36 lines (30 loc) · 787 Bytes
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
import * as h from "@haiyami/hyperstruct";
// Define a struct to validate with.
const User = h.object({
id: h.number(),
name: h.string(),
email: h.string(),
});
type UserType = h.Infer<typeof User>;
// Define data to be validated.
const data: unknown = {
id: 1,
name: true,
email: "jane@example.com",
};
// Test that the data is valid with the `is` helper.
if (h.is(data, User)) {
doSomethingWith(data);
// If you're using TypeScript, the compiler will automatically know that
// inside this block the `data` object has a shape of:
//
// {
// id: number
// name: string
// email: string
// }
}
// Example function to demonstrate type safety
function doSomethingWith(user: UserType): void {
console.log(`User: ${user.name} (${user.email})`);
}