Union and Intersection Types in JSDoc
You'll learn how to express complex type relationships—unions (OR) and intersections (AND)—directly in JSDoc comments using pipe and ampersand syntax.
What This Enables
When type-checking JavaScript with JSDoc, you often need to describe values that can be one of several types (unions) or values that must combine multiple types (intersections). TypeScript's JSDoc support gives you the same expressive power you'd have in .ts files, but using comment syntax.
Union Types with Pipe (|)
The pipe symbol creates a union—a value that can be one type or another:
/**
* @param {string | number} id - accepts either string or number
* @returns {boolean}
*/
function isValidId(id) {
return typeof id === 'string' ? id.length > 0 : id > 0;
}
/**
* @param {null | undefined | string} status
*/
function handleStatus(status) {
if (status) {
console.log(status.toUpperCase());
}
}
You can union as many types as needed: @type {string | number | boolean}.
Intersection Types with Ampersand (&)
The ampersand symbol creates an intersection—a value that must satisfy all combined types:
/**
* @typedef {{name: string}} Named
* @typedef {{age: number}} Aged
*/
/**
* @param {Named & Aged} person - must have both name AND age
*/
function greetPerson(person) {
console.log(`${person.name} is ${person.age}`);
}
Intersections are most useful for combining object shapes or adding capabilities to existing types.
Combining Both
You can mix pipes and ampersands—precedence works like boolean logic:
/**
* @type {(string & {length: number}) | number}
*/
let complexValue;
Key Takeaway: Use the pipe (|) for union types that accept multiple alternatives, and the ampersand (&) for intersection types that require all combined properties—giving your JavaScript the same type expressiveness as TypeScript files.