UNPKG

fortify-schema

Version:

TypeScript interface-like schema validation system that's easier to use than Zod

73 lines (59 loc) • 2.68 kB
import { Interface } from "../schema/mode/interfaces/Interface"; import { When } from "../schema/extensions/components/ConditionalValidation"; console.log("šŸ”§ WHEN.FIELD() TYPESCRIPT INFERENCE TEST"); console.log("=========================================\n"); // Test When.field() with TypeScript inference const WhenFieldSchema = Interface({ role: "admin|user|guest", accountType: "free|premium|enterprise", // šŸ“¦ Import-based When.field() syntax - Should now have TypeScript inference! permissions: When.field("role").is("admin").then("boolean").else("string[]"), maxProjects: When.field("accountType").is("free").then("number").else("number"), paymentMethod: When.field("accountType").isNot("free").then("string").else("string?"), id: "positive", name: "string" }); console.log("āœ… When.field() schema created successfully!"); // Test case 1: Admin user const adminData = { role: "admin" as const, accountType: "premium" as const, permissions: true, // Should be inferred as boolean | string[] (union type) maxProjects: 50, // Should be inferred as number paymentMethod: "credit", // Should be inferred as string | (string | undefined) id: 1, name: "Admin User" }; // Test case 2: Regular user const userData = { role: "user" as const, accountType: "free" as const, permissions: ["read"], // Should be inferred as boolean | string[] (union type) maxProjects: 3, // Should be inferred as number id: 2, name: "Regular User" }; // Test validation const adminResult = WhenFieldSchema.safeParse(adminData); const userResult = WhenFieldSchema.safeParse(userData); console.log("āœ… Admin validation:", adminResult.success); console.log("āœ… User validation:", userResult.success); // Test type errors - these should show TypeScript errors console.log("\nšŸŽÆ Testing TypeScript Error Detection:"); // This should show a TypeScript error if inference is working const invalidData = { role: "admin" as const, accountType: "premium" as const, permissions: 123, // āŒ Should show error: number not assignable to boolean | string[] maxProjects: 50, paymentMethod: "credit", id: 1, name: "Admin User" }; console.log("šŸ”§ WHEN.FIELD() INFERENCE SUMMARY"); console.log("================================="); console.log("āœ… When.field() syntax: Should show union types (boolean | string[])"); console.log("āœ… TypeScript errors: Should catch type mismatches"); console.log("āœ… Runtime validation: Should work correctly"); console.log("\nšŸš€ When.field() TypeScript inference test complete!"); console.log(" Check the IDE to see if permissions shows proper types!");