Cover image

Conditional types ใน TypeScript

14 Aug 2023

Share to:

สวัสดีครับ ในบทความนี้เราจะมาเรียนรู้เรื่อง Conditional types ใน TypeScript ว่าคืออะไร นำไปใช้ประโยชน์ได้อย่างไร

Conditional Types จะช่วยให้เราสามารถกําหนดความสัมพันธ์ระหว่าง input type และ output type

เรามาดูตัวอย่าง Conditional Types ง่ายๆดังนี้ครับ

interface Animal {
  live(): void;
}
interface Dog extends Animal {
  woof(): void;
}

type Example1 = Dog extends Animal ? number : string; // Example1 จะมี type เป็น number
type Example2 = RegExp extends Animal ? number : string; // Example2 จะมี type เป็น string

จาก Code ด้านบน จะเห็นว่า เราสามารถใส่ Condition เพื่อเลือกระหว่าง type string และ number ได้

เพื่อความเข้าใจมากขึ้น เรามาดูอีกตัวอย่างกันครับ

interface IdLabel {
  id: number /* some fields */;
}
interface NameLabel {
  name: string /* other fields */;
}
type NameOrId<T extends number | string> = T extends number ? IdLabel : NameLabel;
// ---cut---
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
  throw 'unimplemented';
}

let a = createLabel('typescript'); // a จะมี type เป็น NameLabel

let b = createLabel(2.8); // a จะมี type เป็น IdLabel

let c = createLabel(Math.random() ? 'hello' : 42); // a จะมี type เป็น NameLabel | IdLabel

จาก Code ด้านบน จะเห็นว่า Return type จาก Function “createLabel” จะขึ้นอยู่กับ Input Parameter ที่รับเข้ามา

Conditional Type Constraints

บางครั้งเราอาจจะจําเป็นต้องกําหนด Condition เพิ่มเติมเข้าไปใน Generic type

ตัวอย่างเช่น ถ้าเราต้องการ Type อะไรก็ได้ที่อย่างน้อยต้องมี property “message” เราสามารถเขียน Code ได้ตามนี้

type MessageOf<T extends { message: unknown }> = T['message'];

interface Email {
  message: string;
}

type EmailMessageContents = MessageOf<Email>;

Suggestion blogs

วิธีดูว่า ubuntu ใช้ Ram ไปเท่าไร

วิธีดูว่า ubuntu ใช้ Ram ไปเท่าไรถ้าเราต้องการที่จะดูว่า ubuntu ของเราใช้ Ram ไปเท่าไรแล้ว และเหลือ ram เท่าไร ให้ใช้คําสั่งนี้

จังหวัดชัยนาท

ประวัติความเป็นมา จังหวัดชัยนาทชัยนาทแปลตามศัพท์มีความหมายว่า "ชัยชนะที่มีเสียงบันลือ" เป็นเมืองโบราณเมืองหนึ่ง ตัวเมืองเดิมอยู่บริเวณฝั่งขวาแม่น้ำเจ้าพระยาที่ปากคลองแพรกศรีราชา ใต้ปากน้ำเก่า สันนิษฐานว่าคงจะสร้างขึ้นในสมัยพญาเลอไทครองกรุงสุโขทัยระหว่าง พ.ศ.

Journaling file system คืออะไร

Journaling file system เป็น file system ที่เก็บการเปลี่ยนแปลงของข้อมูลที่ยังไม่ถูกบันทึกลง system หลัก ซึ่งจะช่วยทําให้ไม่เกิดการสูญหายของข้อมูล เมื่อเกิดปัญหากับ Hardware เช่น ไฟดับ หรือระบบส่วนใดส่วน


Copyright © 2019 - 2024 thiti.dev |  v1.22.0 |  Privacy policy |  status | 

Github profile   Linkedin profile   X profile   Youtube channel   Telegram   Email contact   วงแหวนเว็บ