📘
Type System Deep Dive: Inference and Compatibility
Advanced
130 XP
50 min
Lesson Content
TypeScript Type System Deep Dive
Understanding how TypeScript's type system works under the hood helps you write better, more type-safe code.
Type Inference
// TypeScript infers types
let x = 10; // inferred as number
let y = "hello"; // inferred as string
// Explicit vs inferred
let a: number = 10; // explicit
let b = 10; // inferredStructural Typing
// TypeScript uses structural typing (duck typing)
interface Point { x: number; y: number; }
let point: Point = { x: 10, y: 20 };
let point2 = { x: 10, y: 20, z: 30 }; // Also compatible!Type Compatibility
// Covariance, contravariance, and invariance
// Functions are contravariant in parameters, covariant in returnType Widening and Narrowing
let x = "hello"; // type: string (widened)
const y = "hello"; // type: "hello" (literal, not widened)Example Code
Understanding type inference and compatibility
// Type inference examples
let inferredNumber = 42; // TypeScript infers: number
let inferredString = "hello"; // TypeScript infers: string
// Explicit types
let explicit: number = 42;
let explicitString: string = "hello";
console.log(`Inferred: ${typeof inferredNumber}, Explicit: ${typeof explicit}`);Expected Output:
Inferred: number, Explicit: number
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code