Typescript Foundations / Basic Types

Type inference vs explicit types

πŸ‘‰ 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 null

  • For 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. let x;)

No ambiguity

Best for simple constants

Best for functions, APIs, uninitialized variables