Skip to content

JSTC Examples

Real-world examples and common patterns for using JSTC in your applications.

API Request Validation

Validate incoming API request data:

ts
import JSTC from "@briklab/lib/jstc";

JSTC.setProtectionLevel("hardened");

interface ApiRequest {
  userId: number;
  email: string;
  active: boolean;
}

function validateRequest(data: unknown): data is ApiRequest {
  if (typeof data !== "object" || data === null) return false;
  const d = data as any;
  
  return (
    JSTC.for([d.userId]).check(["number"]) &&
    JSTC.for([d.email]).check(["string"]) &&
    JSTC.for([d.active]).check(["boolean"])
  );
}

const request = { userId: 1, email: "user@example.com", active: true };
console.log(validateRequest(request)); // true

Form Input Validation

Validate form data before submission:

ts
import JSTC from "@briklab/lib/jstc";

JSTC.setProtectionLevel("boundary");

class FormValidator {
  validateEmail(email: unknown): boolean {
    return JSTC.for([email]).check(["string"]);
  }

  validateAge(age: unknown): boolean {
    const isNumber = JSTC.for([age]).check(["number"]);
    return isNumber && (age as number) >= 18;
  }

  validatePhone(phone: unknown): boolean {
    return JSTC.for([phone]).check(["string"]);
  }
}

const validator = new FormValidator();
console.log(validator.validateEmail("user@example.com")); // true
console.log(validator.validateAge(25)); // true

Live Demo - Form Validation

Console
No logs yet.

Configuration Validation

Validate application configuration:

ts
import { JSTypeChecker } from "@briklab/lib/jstc";

interface Config {
  port: number;
  host: string;
  debug: boolean;
  maxConnections: number;
}

const configChecker = new JSTypeChecker("hardened");

function validateConfig(config: unknown): config is Config {
  if (typeof config !== "object" || config === null) return false;
  const c = config as any;
  
  return (
    configChecker.for([c.port]).check(["number"]) &&
    configChecker.for([c.host]).check(["string"]) &&
    configChecker.for([c.debug]).check(["boolean"]) &&
    configChecker.for([c.maxConnections]).check(["number"])
  );
}

const config = {
  port: 3000,
  host: "localhost",
  debug: true,
  maxConnections: 100
};

console.log(validateConfig(config)); // true

Database Record Validation

Validate data before saving to database:

ts
import JSTC from "@briklab/lib/jstc";

JSTC.setProtectionLevel("hardened");

interface User {
  id: number;
  name: string;
  email: string;
  createdAt: string;
}

function isValidUser(user: unknown): user is User {
  if (typeof user !== "object" || user === null) return false;
  const u = user as any;
  
  return (
    JSTC.for([u.id]).check(["number"]) &&
    JSTC.for([u.name]).check(["string"]) &&
    JSTC.for([u.email]).check(["string"]) &&
    JSTC.for([u.createdAt]).check(["string"])
  );
}

const user = {
  id: 1,
  name: "Alice",
  email: "alice@example.com",
  createdAt: "2024-01-01"
};

if (isValidUser(user)) {
  console.log("Valid user record");
  // Save to database
}

Error Handling Pattern

Handle type validation errors gracefully:

ts
import { JSTypeChecker } from "@briklab/lib/jstc";

class ValidationError extends Error {
  constructor(field: string, expectedType: string) {
    super(`Invalid ${field}: expected ${expectedType}`);
    this.name = "ValidationError";
  }
}

const checker = new JSTypeChecker("hardened");

function validateValue(field: string, value: unknown, expectedType: string): void {
  if (!checker.for([value]).check([expectedType as any])) {
    throw new ValidationError(field, expectedType);
  }
}

try {
  validateValue("age", "not a number", "number");
} catch (e) {
  if (e instanceof ValidationError) {
    console.log(e.message); // Invalid age: expected number
  }
}

Next Steps