Course contentsShow
← TypeScript
Lesson 94 of 1,7963. Basic TypesFree lesson

Type Inference with Primitives

See how TypeScript infers primitive types from initial values without annotations.

Type Inference with Primitives

What you'll learn: How TypeScript automatically figures out primitive types without you writing explicit annotations.

The Magic of Inference

You've learned how to write type annotations like let age: number = 25, but here's TypeScript's secret superpower: you often don't need to! When you assign a value to a variable, TypeScript is smart enough to infer (deduce) the type automatically.

let age = 25;  // TypeScript infers: number
let name = "Alice";  // TypeScript infers: string
let isActive = true;  // TypeScript infers: boolean

Even without the : number, : string, or : boolean annotations, TypeScript treats these variables exactly as if you'd written them explicitly. The type checker understands what type each variable holds based on its initial value.

Think of It Like This

Imagine a friend hands you an apple. You don't need them to say "This is an apple" — you can see it's an apple. TypeScript works the same way: if you assign 42, it sees a number. If you assign "hello", it sees a string.

Why This Matters

Type inference keeps your code clean and readable. You get all the safety benefits of static typing without visual clutter. TypeScript still enforces types behind the scenes:

let count = 10;  // inferred as number
count = "twenty";  // Error! Can't assign string to number

Key Takeaway: TypeScript automatically infers primitive types from initial values, giving you type safety without requiring explicit annotations for every variable.