Course contentsShow
← JavaScript
Lesson 2650 of 2,72353. Type Safety Without TypeScriptFree lesson

The Pragmatic Middle Ground

Combining JSDoc for definitions with runtime validation for a balanced type safety approach.

The Pragmatic Middle Ground

What you'll learn: How to blend JSDoc annotations with runtime validation libraries like Zod to achieve practical type safety without TypeScript's build complexity.

The Best of Both Worlds

You don't have to choose between JSDoc's simplicity and runtime validation's guarantees—you can use both together. JSDoc provides development-time type hints in your editor, catching mistakes as you write code. Zod provides runtime validation, ensuring data from external sources (APIs, user input, databases) actually matches your expectations.

Think of it like a security checkpoint at two locations: JSDoc is the metal detector at the door (catches obvious problems early), while Zod is the bag inspection inside (verifies what actually came through).

How They Complement Each Other

Use JSDoc to document your internal function signatures and type shapes. This helps your editor autocomplete correctly and warns you when you pass the wrong arguments within your codebase.

Use Zod schemas at the boundaries where data enters your application—API responses, form submissions, file uploads. Parse incoming data with .parse() or .safeParse(), then work with the validated result knowing its shape is guaranteed.

/** @typedef {import('zod').infer<typeof userSchema>} User */

// Define schema for runtime validation
import { z } from 'zod';
const userSchema = z.object({
  id: z.number(),
  name: z.string()
});

/**
 * @param {User} user - Already validated user object
 * @returns {string}
 */
function greetUser(user) {
  return `Hello, ${user.name}!`; // Editor knows user.name exists
}

// At the boundary: validate
const userData = await fetch('/api/user').then(r => r.json());
const user = userSchema.parse(userData); // Runtime check
greetUser(user); // Type-safe throughout

Key Takeaway: Combine JSDoc for internal type documentation with Zod for external data validation—you get editor intelligence plus runtime safety without a TypeScript compilation step.