TypeScript Type Annotations
Type annotations explicitly tell TypeScript what type a value should be.
Basic Syntax
Use a colon after the variable name to specify the type:
let name: string = "John";
let age: number = 25;
let isActive: boolean = true;
Tip: TypeScript can infer types automatically — annotations are optional when the type is obvious.
Primitive Types
TypeScript supports all JavaScript primitives:
let name: string = "John";
let age: number = 25;
let isActive: boolean = true;
let nothing: null = null;
let missing: undefined = undefined;
let bigNum: bigint = 9007199254740991n;
let symbol: symbol = Symbol("id");
The any Type
any opts a value out of type checking:
let value: any = "Hello";
value = 42; // OK
value = true; // OK
Remember: Only use any when migrating legacy code or dealing with truly unknown data.
The unknown Type
unknown is the type-safe alternative to any:
let value: unknown = "Hello";
// let str: string = value; // Error — must narrow first
if (typeof value === "string") {
console.log(value.toUpperCase()); // OK after narrowing
}
Tip: Prefer unknown over any — it forces you to check the type.
void and never
void = no return value. never = function never returns.
function logMessage(msg: string): void {
console.log(msg);
}
function throwError(msg: string): never {
throw new Error(msg);
}
Array Types
Two syntaxes for typed arrays:
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];
// Readonly arrays
let fixed: readonly number[] = [1, 2, 3];
// fixed.push(4); // Error
Tuple Types
Tuples have fixed types per position:
let person: [string, number] = ["John", 25];
console.log(person[0].toUpperCase()); // "JOHN"
// person[1].toUpperCase(); // Error: number has no toUpperCase
Why tuples? For data with a fixed structure like coordinates or database rows.
Best Practices
- Avoid
any— useunknownor specific types - Always annotate function parameters and return types
- Use
readonlyfor arrays that shouldn’t be modified - Let TypeScript infer when the type is obvious
Common Mistakes
- Using
anyexcessively - Not annotating function return types
- Forgetting
nullandundefinedare different types in strict mode let arr = []infersany[]— always give empty arrays a type