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

Basic Type Annotations with @type

Learn to annotate variables and constants with primitive types using the @type tag.

Basic Type Annotations with @type

What you'll learn: How to add simple type hints to JavaScript variables using JSDoc's @type tag without switching to TypeScript.

The Core Idea

The @type tag lets you declare what kind of value a variable or constant should hold—right in a comment above it. This gives your editor and tools like ESLint the information they need to warn you about potential type mismatches, all while keeping your code pure JavaScript.

Think of @type as a label on a storage container: you're telling everyone (including yourself) "this box should only hold strings" or "this variable is meant to be a number." Your editor can then alert you if you accidentally try to put the wrong thing inside.

Basic Syntax

Place a JSDoc comment directly above the variable declaration:

/** @type {string} */
let username = "alice";

/** @type {number} */
const maxRetries = 3;

/** @type {boolean} */
let isActive = true;

If you later try to assign the wrong type, editors with JSDoc support will underline the error:

/** @type {string} */
let username = "alice";

username = 42; // Editor warns: Type 'number' not assignable to 'string'

Why This Matters

You get some of TypeScript's safety net without adding a build step. Variables become self-documenting, and your team immediately knows what data types functions expect. It's particularly useful in large codebases where a variable's intended type isn't obvious from its name alone.

Key Takeaway: The @type tag annotates variables with primitive types like string, number, and boolean, enabling type checking and autocomplete in JavaScript without TypeScript compilation.