S SmartDocs
Serie: Typescript typescript 108 righe · Aggiornato 2025-12-27

06-type-guards.ts

Typescript/src/02-intermediate/06-type-guards.ts

// ============================================
// 06. Type Guards
// ============================================

// typeof Type Guards
function process(value: string | number) {
  if (typeof value === "string") {
    // TypeScript knows value is string here
    console.log(value.toUpperCase());
  } else {
    // TypeScript knows value is number here
    console.log(value.toFixed(2));
  }
}

// instanceof Type Guards
class Dog {
  bark(): void {
    console.log("Woof!");
  }
}

class Cat {
  meow(): void {
    console.log("Meow!");
  }
}

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark(); // TypeScript knows it's a Dog
  } else {
    animal.meow(); // TypeScript knows it's a Cat
  }
}

// in Operator Type Guards
interface DogInterface {
  type: "dog";
  bark(): void;
}

interface CatInterface {
  type: "cat";
  meow(): void;
}

function makeSound2(pet: DogInterface | CatInterface) {
  if ("bark" in pet) {
    pet.bark(); // TypeScript knows it's a DogInterface
  } else {
    pet.meow(); // TypeScript knows it's a CatInterface
  }
}

// User-Defined Type Guards
interface Fish {
  swim(): void;
}

interface Bird {
  fly(): void;
}

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim(); // TypeScript knows it's a Fish
  } else {
    pet.fly(); // TypeScript knows it's a Bird
  }
}

// Type Guard with Discriminated Union
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number };

function isCircle(shape: Shape): shape is { kind: "circle"; radius: number } {
  return shape.kind === "circle";
}

function area(shape: Shape): number {
  if (isCircle(shape)) {
    return Math.PI * shape.radius ** 2;
  } else {
    return shape.width * shape.height;
  }
}

// Assertion Functions
function assertIsNumber(value: unknown): asserts value is number {
  if (typeof value !== "number") {
    throw new Error("Expected number");
  }
}

function processValue(value: unknown) {
  assertIsNumber(value);
  // TypeScript knows value is number here
  console.log(value.toFixed(2));
}

export { process, makeSound, move, area, processValue };

Articoli correlati