بتل کد Battle Codeدارد باز می‌شود…

جلسه‌ی 27: با شرط With Conditions

یاد می‌گیری برای برچسب T شرط بگذاری: «هر نوعی، به شرطی که id داشته باشد». با keyof اسم فیلدهای یک شکل را می‌گیری و با <T, K extends keyof T> تابعی می‌نویسی که غلط املایی در اسم فیلد را هم می‌گیرد.

در این جلسه یاد می‌گیری

درس

علی می‌خواهد تابعی بنویسد که شماره‌ی هر چیزی را نشان بدهد: بازیکن، کتاب، هر چیزی. پس آن را جنریک نوشت. ولی اجرا کن: روی item.id خط قرمز است. چرا؟ چون T یعنی «هر نوعی». شاید کسی یک عدد یا یک متن به این تابع بدهد. عدد که id ندارد! تایپ‌اسکریپت می‌گوید: «من از T هیچ چیز نمی‌دانم، پس نمی‌گذارم از آن id بخواهی».

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
function showId<T>(item: T): void {
  show(item.id);
}

showId({ id: 7, name: "Sara" });
</script>

باشگاه را تصور کن: هر کسی می‌تواند وارد شود، به شرطی که کارت عضویت داشته باشد. برای T هم می‌شود شرط گذاشت. <T extends { id: number }> یعنی «T هر نوعی می‌تواند باشد، به شرطی که یک id عددی داشته باشد». کلمه‌ی extends را از شکل‌ها و کلاس‌ها می‌شناسی؛ این‌جا یعنی «دست‌کم این را دارد». حالا تایپ‌اسکریپت مطمئن است که item.id وجود دارد. اجرا کن.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
function showId<T extends { id: number }>(item: T): void {
  show(item.id);
}

showId({ id: 7, name: "Sara" });
showId({ id: 3, title: "Matilda", pages: 240 });
</script>

و اگر کسی بدون کارت بیاید؟ این‌جا به showId یک متن داده‌ایم. متن id ندارد، پس شرط را ندارد. اجرا کن: خط قرمز، این بار سر جای درستش، یعنی همان خطی که تابع را غلط صدا زده است.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
function showId<T extends { id: number }>(item: T): void {
  show(item.id);
}

showId("Sara");
</script>

شاید بپرسی: چرا ننویسیم item: { id: number } و خلاص؟ چون آن‌وقت تابع بقیه‌ی فیلدها را فراموش می‌کند. این تابع را ببین: از بین یک لیست، چیزی را که id آن را داده‌ای پیدا می‌کند. جوابش T | undefined است (شاید پیدا نشود). چون T این‌جا Player است، بعد از if می‌توانی found.name را بخوانی. جنریک، نوع کامل را نگه داشته است.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Player {
  id: number;
  name: string;
}

function findById<T extends { id: number }>(list: T[], id: number): T | undefined {
  for (const item of list) {
    if (item.id === id) {
      return item;
    }
  }
  return undefined;
}

const players: Player[] = [
  { id: 1, name: "Sara" },
  { id: 2, name: "Ali" },
];

const found = findById(players, 2);
if (found !== undefined) {
  show(found.name);
}
</script>

حالا یک کلمه‌ی تازه: keyof. فرم ثبت‌نام را تصور کن که چند خانه دارد: «نام»، «امتیاز». keyof Player یعنی «اسم یکی از خانه‌های Player». برای این شکل، keyof Player همان "name" | "score" است: یک union از مقدارهای دقیق، که در جلسه‌ی ۱۷ دیدی. با این فرق که خودت آن را ننوشته‌ای؛ تایپ‌اسکریپت از روی شکل درستش می‌کند.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Player {
  name: string;
  score: number;
}

const sara: Player = { name: "Sara", score: 40 };

let field: keyof Player = "name";
show(sara[field]);
field = "score";
show(sara[field]);
</script>

و اگر اسمی بنویسی که در شکل نیست؟ Player خانه‌ای به اسم age ندارد. اجرا کن و خط قرمز را ببین. این یعنی دیگر نمی‌شود اسم یک فیلد را غلط نوشت و نفهمید.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Player {
  name: string;
  score: number;
}

const field: keyof Player = "age";
show(field);
</script>

حالا این دو را با هم جمع می‌کنیم. یک تابع می‌تواند دو برچسب داشته باشد، با یک ویرگول بینشان. در <T, K extends keyof T>، T نوع خودِ چیز است و K اسم یکی از فیلدهای آن. شرطِ K این است: «باید یکی از اسم فیلدهای T باشد». نوع جواب T[K] است، یعنی «نوعِ همان فیلد». برای "name" می‌شود string و برای "score" می‌شود number. برای همین خط آخر می‌تواند با امتیاز جمع بزند.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
function getField<T, K extends keyof T>(item: T, key: K): T[K] {
  return item[key];
}

const sara = { name: "Sara", score: 40 };

show(getField(sara, "name"));
show(getField(sara, "score") + 1);
</script>

و جایزه‌ی این همه زحمت: غلط املایی. این‌جا به‌جای "score" نوشته‌ایم "scroe". در جاوااسکریپت جواب بی‌صدا undefined می‌شد. این‌جا خط قرمز می‌بینی، چون "scroe" اسم هیچ‌کدام از فیلدهای sara نیست. اشتباه رایج: keyof را بدون extends می‌نویسند (<T, K keyof T>). یادت باشد: شرط همیشه با extends می‌آید.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
function getField<T, K extends keyof T>(item: T, key: K): T[K] {
  return item[key];
}

const sara = { name: "Sara", score: 40 };

show(getField(sara, "scroe"));
</script>

مثال‌های این جلسه

چالش‌ها

  1. Only with an id (آسان)
  2. The Name of a Field (آسان)
  3. The Newer One (متوسط)
  4. Read a Field (متوسط)
  5. Find the Red Lines (سخت)
  6. Set a Field (سخت)

بیشتر بخوان

← جلسه‌ی 26: یک تابع برای همه‌ی نوع‌ها جلسه‌ی 28: شکل‌های جنریک →