DG
DevGuide
Run Code
Home/TypeScript/Basic Types & Annotations
TS TypeScript1 / 4

Basic Types & Annotations

📌 WHAT

TypeScript adds static type annotations to JavaScript. You tell TypeScript what type each variable, parameter, and return value should be — and it catches mismatches before your code runs.

💡 WHY

Catches bugs at compile time instead of runtime. Provides IDE autocomplete and documentation. Makes large codebases maintainable. Required in most modern React/Next.js projects.

⏰ WHEN / WHERE

In any TypeScript file (.ts or .tsx). Type annotations are optional but recommended everywhere. TypeScript can infer many types automatically.

🔧 HOW

Add : type after variable names, parameters, and function signatures. TypeScript infers types when possible — only annotate when inference isn't clear.

Code Examples

#1Core type annotations

Core type annotations
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// TypeScript infers types automatically — you don't always need to annotate
let name = "Ali"; // inferred as string
let age = 25; // inferred as number
let active = true; // inferred as boolean
// Explicit annotations
let username: string = "Ali";
let score: number = 100;
let isLoggedIn: boolean = false;
let data: null = null;
let x: undefined = undefined;
// Arrays
let scores: number[] = [90, 85, 92];
let names: string[] = ["Ali", "Ahmed"];
let mixed: (string | number)[] = ["Ali", 25]; // union type in array
// Tuple — fixed length array with specific types at each position
let point: [number, number] = [10, 20];
let person: [string, number] = ["Ali", 25];
// any — escape hatch, avoid!
let anything: any = "could be anything";
anything = 42; // no error — any allows this
anything.foo.bar; // no error — TypeScript gives up on checking
// unknown — safer than any
let value: unknown = getData();
if (typeof value === "string") {
console.log(value.toUpperCase()); // ✅ must check type first
}
// void — function that returns nothing
function logMessage(msg: string): void {
console.log(msg);
// no return statement needed
}
// never — function that NEVER returns (throws or infinite loop)
function throwError(message: string): never {
throw new Error(message);
}

Practice This Concept

Open the playground, paste any example, and experiment. The best way to learn is by breaking things.

Open in Playground