หัวข้อ 3: TypeScript ประเภทข้อมูล Interface และ Type Alias

คำจำกัดความ

TypeScript คือ JavaScript ที่เพิ่ม Static Type Checking ช่วยตรวจชนิดข้อมูลก่อนรันจริง ลด error และทำให้ editor ช่วย autocomplete ได้ดีขึ้น

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart LR
  A["TypeScript Code
โค้ดมี Type"] --> B["tsc Compiler
ตรวจชนิดข้อมูล"] B --> C["JavaScript Code
โค้ดที่ Browser/Node รันได้"] B --> D["Type Errors
แจ้งเตือนก่อนรัน"]

ติดตั้ง TypeScript

npm install -g typescript
tsc --init

Basic Types

Type ใช้กับ ตัวอย่าง
string ข้อความ "Ana"
number ตัวเลข 42
boolean จริง/เท็จ true
any ปิดการตรวจ type ควรหลีกเลี่ยง
unknown ไม่รู้ชนิด ต้องตรวจก่อนใช้ ปลอดภัยกว่า any
never ไม่มีวันคืนค่า throw/error loop
void ไม่คืนค่า function ที่ไม่ return
let title: string = "Web Programming";
let credit: number = 3;
let active: boolean = true;

function logMessage(message: string): void {
  // แสดงข้อความโดยไม่คืนค่า
  console.log(message);
}

logMessage(`${title} ${credit} credits`);

Union และ Intersection

type Id = string | number;

type HasName = { name: string };
type HasEmail = { email: string };
type UserContact = HasName & HasEmail;

const user: UserContact = {
  name: "Ana",
  email: "ana@example.com"
};

Interface

interface User {
  readonly id: number;
  name: string;
  age?: number;
}

const user: User = {
  id: 1,
  name: "Ana"
};

console.log(user.name);

Type Alias

type Point = {
  x: number;
  y: number;
};

const point: Point = { x: 10, y: 20 };

Generics

Generics ทำให้ function/class ใช้ type เป็น parameter ได้

function identity<T>(arg: T): T {
  // คืนค่าชนิดเดียวกับที่รับเข้าไป
  return arg;
}

const text = identity<string>("Hello");
const amount = identity<number>(100);

console.log(text, amount);

สมการ Type Coverage อย่างง่าย

C = typed total × 100

โดยที่ C คือเปอร์เซ็นต์ type coverage, typed คือจำนวนส่วนที่ระบุ type แล้ว, และ total คือจำนวนส่วนทั้งหมด

แบบทดสอบหลังเรียน

  1. any และ unknown ต่างกันอย่างไร
  2. Union Type ใช้ทำอะไร
  3. Optional property เขียนอย่างไร
  4. Interface และ Type Alias ต่างกันในภาพรวมอย่างไร
  5. Generics ช่วยให้ function ยืดหยุ่นอย่างไร

กลับสัปดาห์ที่ 6