Type Annotations
Type Annotations
Section titled “Type Annotations”What it means
Section titled “What it means”Type annotations explicitly declare the type of variables, parameters, and return values. This is the foundation of TypeScript’s type system, enabling compile-time type checking.
Examples
Section titled “Examples”// Variableslet name: string = "Alice";let age: number = 25;let isActive: boolean = true;let nothing: null = null;let notDefined: undefined = undefined;
// Arrayslet numbers: number[] = [1, 2, 3];let strings: Array<string> = ["a", "b", "c"];
// Functionsfunction greet(name: string): string { return `Hello, ${name}!`;}
// Arrow functionsconst add = (a: number, b: number): number => a + b;
// Objectslet user: { name: string; age: number } = { name: "Bob", age: 30};Common mistake
Section titled “Common mistake”Mixing types unintentionally:
// BADlet value: string = "hello";value = 42; // Error: Type 'number' is not assignable to type 'string'
// GOOD - use union type if neededlet value: string | number = "hello";value = 42; // OKFix: Be consistent with types or use union types when multiple types are valid.
Quick practice
Section titled “Quick practice”-
Annotate:
function multiply(x, y) { return x * y; }Answer
`function multiply(x: number, y: number): number { return x * y; }` -
What type would you use for an array of booleans?
Answer
`boolean[]` or `Array` -
Create a variable that can be either a string or null
Answer
`let value: string | null = null;`