۶

انواع پیشرفته (Advanced Types)

آشنایی با Union, Intersection و Literal Types.

Union Types: این یا اون!

با Union Type (که با علامت `|` نشون داده می‌شه) می‌تونیم بگیم یه متغیر یا پارامتر می‌تونه چند نوع مختلف داشته باشه.

function printId(id: number | string) {
  console.log("Your ID is: " + id);
  // console.log(id.toUpperCase()); // Error! id might be a number.
  if (typeof id === "string") {
    // حالا تایپ‌اسکریپت مطمئنه که id رشته است
    console.log(id.toUpperCase());
  }
}

printId(101);
printId("abc");

Intersection Types: این و اون!

با Intersection Type (که با علامت `&` نشون داده می‌شه) می‌تونیم چندتا تایپ رو با هم ترکیب کنیم و یه تایپ جدید بسازیم که همه ویژگی‌های تایپ‌های اولیه رو داشته باشه.

interface Colorful {
  color: string;
}
interface Circle {
  radius: number;
}

type ColorfulCircle = Colorful & Circle;

const myCircle: ColorfulCircle = {
  color: "blue",
  radius: 10.5,
};

Literal Types: فقط همین مقادیر!

گاهی وقتا می‌خوایم یه متغیر فقط بتونه چندتا مقدار خاص و مشخص رو قبول کنه.

type Alignment = "left" | "right" | "center";

let textAlign: Alignment = "center";
// textAlign = "middle"; // Error! Type '"middle"' is not assignable to type 'Alignment'.

تمرین! 🧠

یه Type Alias به اسم `StatusCode` بساز که فقط بتونه مقادیر عددی `200`, `404`, یا `500` رو قبول کنه. بعد یه تابع به اسم `handleResponse` بنویس که یه پارامتر از نوع `StatusCode` بگیره و بر اساس مقدارش، یه پیام مناسب تو کنسول چاپ کنه.

جواب تمرین

type StatusCode = 200 | 404 | 500;

function handleResponse(code: StatusCode) {
  if (code === 200) {
    console.log("OK: درخواست موفق بود.");
  } else if (code === 404) {
    console.log("Not Found: منبع پیدا نشد.");
  } else {
    console.log("Internal Server Error: خطای داخلی سرور.");
  }
}

handleResponse(200);
// handleResponse(301); // Error! Argument of type '301' is not assignable to parameter of type 'StatusCode'.