TypeScript-Style Annotations on Destructured Params
You'll learn how to add JSDoc type hints to destructured parameters for better code documentation and IDE support.
The Problem with Destructured Parameters
When you destructure function parameters, your code becomes more concise but less self-documenting. Someone reading your function signature might not immediately know what types the destructured properties should be. This is where JSDoc comments come in handy.
Adding Type Annotations with JSDoc
Even in plain JavaScript, you can annotate destructured parameters using JSDoc syntax. This gives you TypeScript-like benefits without actually using TypeScript:
/**
* @param {Object} options - The configuration object
* @param {string} options.name - User's name
* @param {number} options.age - User's age
* @param {boolean} [options.isActive] - Optional active status
*/
function createUser({ name, age, isActive = true }) {
return { name, age, isActive };
}
// Your IDE will now provide hints and warnings!
createUser({ name: "Alice", age: 30 }); // ✓
// createUser({ name: "Bob", age: "thirty" }); // IDE warns: age should be number
How It Helps
Think of JSDoc as writing instruction labels on your function's inputs. Even though JavaScript won't enforce these types at runtime, your code editor can read these annotations and:
- Show helpful autocomplete suggestions
- Warn you when you pass the wrong type
- Provide inline documentation when you hover over the function
This approach bridges the gap between JavaScript's flexibility and TypeScript's strictness, giving you better tooling without adding a build step.
Key Takeaway: Use JSDoc comments to annotate destructured parameters with type information, improving code documentation and enabling IDE features like type checking and autocomplete in plain JavaScript.