TypeScript Type Annotations: Defining Your Data's Shape
Type annotations are contracts for your data, telling TypeScript what to expect from variables and functions. You'll use them for primitives like `string` or `number`, and for arrays like `string[]`.
WHY IT EXISTS: JavaScript is dynamically typed, meaning type errors often surface only at runtime. Type annotations are TypeScript's core feature for adding a static type system, allowing you to declare what kind of data a variable holds and catch mismatches during development, not in production.
THE MENTAL MODEL: Think of a type annotation as a contract or a label for your data. By writing let name: string;, you are telling the TypeScript compiler, "This variable name must always hold a string." The compiler then acts as a vigilant assistant, ensuring this contract is never broken anywhere in your code.
HOW IT WORKS: You add an annotation using a colon : followed by the type. TypeScript includes types for JavaScript's primitives: string for text like "Hello", number for all numbers like 42 or 3.14, and boolean for true or false. For arrays, you can write number[] for an array of numbers or use the generic syntax Array<number>. These annotations are only for the compiler; they are completely erased when TypeScript compiles your code down to plain JavaScript, adding no runtime overhead.
WHEN TO USE IT: Explicitly annotate function parameters and return values to create clear API boundaries. It's also good practice to annotate variables when their type isn't immediately inferred from an initial value. This makes the code self-documenting and easier for others (and your future self) to understand.
WHEN NOT TO USE IT: Don't add annotations when TypeScript can easily infer the type, such as let name = "Alice";. TypeScript already knows name is a string. The most critical footgun is overusing the any type. While any can be a temporary escape hatch, it disables type checking and undermines the safety benefits of TypeScript. Also, always use the lowercase primitive types (string, number) instead of the capitalized versions (String, Number), which are special built-in types you rarely need.
ONE CANONICAL EXAMPLE: Consider a function greet(person: string, date: Date): string. This annotation declares that the function greet accepts a person of type string and a date of type Date, and it must return a string. Calling it with greet("Alice", new Date()) is valid. If you were to call greet(123, "2024-01-01"), TypeScript would throw a compile-time error, preventing a bug before the code is ever run.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.