TypeScript Inference


TypeScript: Type Inference

TypeScript is smart enough to figure out the type of a variable even if you don’t tell it.


What Is Type Inference?

When you create a variable and assign a value to it, TypeScript automatically understands what type it is—without needing you to say it.

It watches what you write and makes an educated guess. That’s called type inference.

Example:

let message = "Hello"; 

You didn’t write : string, but TypeScript sees that "Hello" is a string, so it treats message as a string.

Now, if you try this:

message = 123; // ❌ Error! Type 'number' is not assignable to type 'string' 

It stops you—because message was inferred as a string, not a number.

Another Example

let total = 100; 

Since 100 is a number, TypeScript knows total should stay a number.


When Should You Use It?

You can rely on type inference for simple variables, constants, and function returns. It keeps your code cleaner while still protecting you from mistakes.

But for complex structures or shared code, it's better to explicitly define types for clarity.


Tip

TypeScript balances safety with convenience — it won’t ask you to write types everywhere unless needed.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:

What You'll Learn:
  • 📌 Typescript - 3. Type Inference
  • 📌 Type Annotation & Type Inference | String Templates | TypeScript Tutorial
Previous Next