Conditional types ใน TypeScript

14 Aug 2023,
Share: 
Cover image

สวัสดีครับ ในบทความนี้เราจะมาเรียนรู้เรื่อง 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

วิธีป้องกันสแปมรบกวนใน iMessage

สําหรับผู้ใช้งาน iPhone ในช่วงนี้ได้รับข้อความสแปมใน iMessage ทําให้บางคนเกิมความกังวลในเรื่องของความปลอดภัย และเกิดความรำคาญ ในความเป็นจริงแล้วเราไม่ต้องสนใจ ไม่ต้องไปกด Link ต่างๆที่ส่งเข้ามาก็ได้ครับ ไม่มีผลกระทบใดๆกับเครื่องของเราแต่อย่างใด แต่สําหรับใครที่ยังรำคาญ เราก็สามารถ Setting เพื่อโยนข้อความ iMessage ที่ถูกส่งมาจากบุคคลอื่น (บุคคลที่ไม่ได้อยู่ในรายชื่อใน Contact ของเรา) แยกไปอยู่ใน Unknown Senders และก็จะไม่มีการแจ้งเตือนให้หน้ารําคาญ สามารถ Setting ได้ตามวิธีดังนี้ครับ

ทําความรู้จักกับ Plickers

Plickers (Paper + Clicker) เป็นเครื่องมือที่ช่วยให้อาจารย์ Check ความเข้าใจในเนื้อหาของนักเรียนใน Class ที่ตนเองสอน ได้อย่างง่ายดาย

HTTP status codes

error code หรือ status code ที่ server ส่งกลับมาเมื่อเราเปิดเว็บ จะมีความหมายดังนี้


Copyright © 2019 - 2025 thiti.dev |  v1.58.0 |  Privacy policy | 

Build with ❤️ and Astro.

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