</>
Skip to content
TypeScript lessons (8/31)

TypeScript — Type Inference

Type guards

function isString(value: unknown): value is string {
  return typeof value === 'string';
}

function process(value: string | number) {
  if (isString(value)) {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }
}

Discriminated unions

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rectangle'; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'rectangle':
      return shape.width * shape.height;
  }
}

Exhaustive checking

function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${value}`);
}

function processShape(shape: Shape) {
  switch (shape.kind) {
    case 'circle': return Math.PI * shape.radius ** 2;
    case 'rectangle': return shape.width * shape.height;
    default: return assertNever(shape);
  }
}

Mini Practice

Write TypeScript code that:

  1. Creates a type guard function
  2. Uses discriminated unions
  3. Demonstrates exhaustive checking
  4. Narrows types with typeof and instanceof

Up Next

In the next lesson, you'll learn about Error Handling — Result types and error patterns.

Related Topics

Frequently Asked Questions about Type Inference

What is Type Inference in TypeScript?

Type Inference is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Type Inference?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Type Inference.

Why is Type Inference important in TypeScript?

Type Inference is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.