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

Array and Generic Types

Annotate arrays with specific element types and use generic syntax for typed collections.

Array and Generic Types

You'll learn how to annotate arrays with precise element types and use generic syntax to make your JSDoc annotations flexible and type-safe.

Why Array Types Matter

In vanilla JavaScript with JSDoc, you can specify what kind of things live inside an array. A plain @type {Array} tells you almost nothing—is it strings? Numbers? Objects? Generic types let you be specific: Array<string> means "an array of strings only."

Basic Array Annotations

You have two equivalent syntaxes:

/** @type {string[]} */
const names = ['Alice', 'Bob'];

/** @type {Array<number>} */
const scores = [95, 87, 92];

Both work identically. The [] suffix is shorthand; Array<...> is the explicit generic form.

Generic Collections

Generics work with other built-in types too:

/** @type {Set<number>} */
const uniqueIds = new Set([1, 2, 3]);

/** @type {Map<string, number>} */
const ages = new Map([['Alice', 30], ['Bob', 25]]);

The syntax <...> fills in the "placeholder" type. Map<K, V> needs two types: keys and values.

Arrays of Complex Types

Combine arrays with your custom @typedef types:

/**
 * @typedef {Object} User
 * @property {string} name
 * @property {number} age
 */

/** @type {User[]} */
const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 }
];

Now your editor knows each element has name and age properties.

Key Takeaway: Use Type[] or Array<Type> to annotate array contents, and apply the same generic syntax (<...>) to other collections like Set and Map for complete type safety without TypeScript.