Skip to content

Type Annotations

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.

// Variables
let name: string = "Alice";
let age: number = 25;
let isActive: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;
// Arrays
let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ["a", "b", "c"];
// Functions
function greet(name: string): string {
return `Hello, ${name}!`;
}
// Arrow functions
const add = (a: number, b: number): number => a + b;
// Objects
let user: { name: string; age: number } = {
name: "Bob",
age: 30
};

Mixing types unintentionally:

// BAD
let value: string = "hello";
value = 42; // Error: Type 'number' is not assignable to type 'string'
// GOOD - use union type if needed
let value: string | number = "hello";
value = 42; // OK

Fix: Be consistent with types or use union types when multiple types are valid.

  1. Annotate: function multiply(x, y) { return x * y; }

    Answer`function multiply(x: number, y: number): number { return x * y; }`
  2. What type would you use for an array of booleans?

    Answer`boolean[]` or `Array`
  3. Create a variable that can be either a string or null

    Answer`let value: string | null = null;`