Type Inference
TypeScript Type System•Section 3 of 4•beginner
Topic Overview
Take your time to understand each concept. Practice with the examples below!
TypeScript is smart! It can often figure out types on its own without you having to write them. This is called type inference, and it makes your code cleaner while keeping it safe.
What is Type Inference? When you assign a value to a variable, TypeScript looks at that value and automatically determines its type. It's like TypeScript is a detective, gathering clues about your data!
Basic Inference Examples:
- •let name = "Alice" → TypeScript knows it's a string
- •let age = 25 → TypeScript knows it's a number
- •let isActive = true → TypeScript knows it's a boolean
- •let items = [1, 2, 3] → TypeScript knows it's number[]
Function Return Type Inference:
TypeScript can figure out what a function returns based on its code:
- •Simple returns:function add(a: number, b: number) { return a + b } → returns number
- •Conditional returns:Different return statements? TypeScript finds the common type
- •Object returns:Returns an object? TypeScript infers its shape
When to Use Explicit Types vs Inference:
Use Inference When:
- •The type is obvious from the value
- •Working with simple variables
- •Function return types are clear
- •You want cleaner, less verbose code
Use Explicit Types When:
- •Defining function parameters
- •Creating empty arrays or objects
- •The type isn't obvious from context
- •You want to document complex types
- •Working in a team (explicit types help others)
Best Practices:
- •Let TypeScript infer simple types
- •Be explicit with function parameters
- •Use explicit types for public APIs
- •Trust the inference for local variables
Example
// Type inference in actionlet name = "Alice"; // TypeScript infers: stringlet age = 25; // TypeScript infers: numberlet isActive = true; // TypeScript infers: booleanlet numbers = [1, 2, 3]; // TypeScript infers: number[]// Function return type inferencefunction add(x: number, y: number) { return x + y; // TypeScript infers return type: number}function getUser() { return { id: 1, name: "John", email: "john@example.com" }; // TypeScript infers: { id: number; name: string; email: string; }}// Best common typelet mixedArray = [1, "hello", true]; // TypeScript infers: (string | number | boolean)[]// Contextual typingwindow.onmousedown = function(mouseEvent) { // mouseEvent parameter type is inferred from context console.log(mouseEvent.button);};const user = getUser();console.log(`User: ${user.name} (${user.email})`);