Type Annotations
In this page:
String Annotations
Use the string type annotation, written as name: string, when a variable should hold text data. Once annotated this way, assigning anything other than a string to that variable becomes a compile-time error.
Example: String Annotations
let name: string = "Neel";
// name = 42; // rejected: number is not a string
console.log(name);
Number and Boolean Annotations
The number and boolean types describe numeric values and true-or-false values respectively, using the same simple name: type annotation syntax. TypeScript uses a single number type for both integers and decimals, unlike languages with separate int and float types.
Example: Number and Boolean Annotations
let age: number = 30;
let isMember: boolean = true;
console.log(age, isMember);
Array Annotations
Array annotations, written as type[], specify the type every single element stored in that array must match, such as string[] for an array of text values. This lets the compiler catch a mismatched item the moment it's added, not just when it's later used.
Example: Array Annotations
let tags: string[] = ["ts", "types"];
// tags.push(42); // rejected: number is not a string
console.log(tags);
Object Annotations
Object type annotations describe the properties an object must have and the type each property's value must match, either inline or through a named interface. This documents an object's expected shape directly in the code, rather than leaving it implicit.
Example: Object Annotations
interface Book {
title: string;
pages: number;
}
let book: Book = { title: "TypeScript Basics", pages: 200 };
console.log(book);
Why Type Annotations Matter
Type annotations across all of these make the intended type of a piece of data explicit at the point of declaration, rather than something a reader has to infer. This lets TypeScript detect an invalid value being assigned the moment it happens during development, instead of surfacing as a bug later.
Example: Why Type Annotations Matter
let quantity: number = 5;
// quantity = "five"; // caught immediately, not discovered later at runtime
console.log(quantity);
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: