fortify-schema
Version:
TypeScript interface-like schema validation system that's easier to use than Zod
73 lines (59 loc) ⢠2.68 kB
text/typescript
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!");