π TypeScript automatically figures out (infers) the type based on the assigned value.
π You donβt have to explicitly write the type β TypeScript does it for you.
β Example β Type Inference:
let name = "Alice"; // inferred as string
let age = 25; // inferred as number
let isAdmin = false; // inferred as booleanβ‘ TypeScript infers:
// name: string
// age: number
// isAdmin: booleanβ If you try:
name = 42; // TypeScript will error: Type 'number' is not assignable to type 'string'β The compiler protects you based on inferred types!
π What are Explicit Types?
π You manually specify the type in your code.
π This is useful when:
The compiler canβt infer the correct type
You want to be more explicit for readability
You're working with function parameters/returns or complex structures
β Example β Explicit Types:
let name: string = "Alice";
let age: number = 25;
let isAdmin: boolean = false;
let user: { name: string; age: number } = { name: "Alice", age: 25 };π Even without assignment, the variable has a type:
let price: number;
price = 100; // β
OK
price = "cheap"; // β Errorπ When to use each?
Scenario | Type Inference | Explicit Types |
|---|---|---|
Simple value assignment | β Good enough | β Optional if you want clarity |
Function parameters | β TS canβt infer, so you should specify | β Always specify |
Function return types | TS tries to infer, but explicit is clearer (especially in public APIs) | β Recommended |
Complex objects | TS can often infer, but explicit helps readability | β Good practice |
Uninitialized variables | β No inference | β You must specify |
π‘ Best practices
β Type inference is great for simple cases β keeps code clean.
β Explicit types are best:
For function signatures
When variables start undefined or
nullFor object/array structures
For public APIs (functions, classes)
β Be consistent within your project/team!
π Summary
Type Inference | Explicit Types |
|---|---|
TypeScript figures out type from value | You declare the type manually |
Less code to write | More readable, self-documenting |
Risk of unintended widening (e.g. | No ambiguity |
Best for simple constants | Best for functions, APIs, uninitialized variables |