TypeScript: Types & Annotations
What you will learn
How to add type annotations to variables, how TypeScript infers types, and how union types let a variable hold multiple types.
TypeScript is a superset of JavaScript that adds static type checking. Your TypeScript code compiles (transpiles) to plain JavaScript that runs anywhere JS runs.
Variable annotations
let name: string = 'Alice';
let age: number = 25;
let isActive: boolean = true;
let items: string[] = ['a', 'b']; // array of strings
let anything: any = 'could be anything'; // any disables checking
The colon : type syntax tells TypeScript what type a variable is. If you assign a value of the wrong type later, the compiler (or your editor) will flag it.
Type inference
You don't always need to write the type. TypeScript infers it from the initial value:
let message = 'Hello'; // inferred as string
let count = 42; // inferred as number
let isValid = true; // inferred as boolean
Hover over message in VS Code -- it shows let message: string. Inference is your friend; use explicit annotations only when inference isnt enough.
Union types
A variable can be one of several types using |:
let id: string | number;
id = 'abc123'; // OK
id = 456; // OK
// id = true; // Error: boolean not allowed
Arrays and Tuples
let names: string[] = ['Alice', 'Bob'];
let first: number[] = [1, 2, 3];
// Tuple -- fixed-length array with typed positions
let pair: [string, number] = ['Alice', 25];
Common mistakes
- Forgetting that
nullandundefinedarent included in most types unless you use a union:string | null - Overusing
any-- it defeats the purpose of TypeScript. Preferunknownif you really cant know the type ahead of time.
Quick check below!