TypeScript classes and modules


Classes in TypeScript

Classes ใน TypeScript เป็นวิธีการสร้างออบเจ็กต์ที่มีโครงสร้างและพฤติกรรมที่กำหนดไว้ล่วงหน้า โดยอิงจากหลักการของ Object-Oriented Programming (OOP) การใช้ Classes ช่วยให้เราสามารถจัดกลุ่มข้อมูล (properties) และพฤติกรรม (methods) ที่เกี่ยวข้องกันไว้ในที่เดียว

ตัวอย่างการสร้าง Class ใน TypeScript:

class Person {
  private name: string;
  private age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  public getDetails(): string {
    return `Name: ${this.name}, Age: ${this.age}`;
  }
}

const john = new Person('John', 30);
console.log(john.getDetails()); // Output: "Name: John, Age: 30"

TypeScript ยังรองรับการสืบทอด (inheritance) ระหว่าง Classes ด้วย ซึ่งช่วยให้เราสามารถสร้าง Class ใหม่จาก Class ที่มีอยู่แล้วและขยายหรือปรับแต่งพฤติกรรมได้

class Student extends Person {
  private studentId: string;

  constructor(name: string, age: number, studentId: string) {
    super(name, age);
    this.studentId = studentId;
  }

  public getDetails(): string {
    return `${super.getDetails()}, Student ID: ${this.studentId}`;
  }
}

const jane = new Student('Jane', 20, 'S1234');
console.log(jane.getDetails()); // Output: "Name: Jane, Age: 20, Student ID: S1234"

Modules in TypeScript

Modules ใน TypeScript ช่วยให้เราสามารถแบ่งโค้ดออกเป็นไฟล์ต่างๆ ได้ โดยแต่ละไฟล์จะมีขอบเขตของตัวเอง (own scope) ซึ่งช่วยหลีกเลี่ยงปัญหาการใช้ชื่อตัวแปรซ้ำกันและทำให้โค้ดมีการจัดระเบียบที่ดีขึ้น

ในการสร้าง Module เราใช้คีย์เวิร์ด export เพื่อกำหนดว่าส่วนใดของโค้ดที่สามารถเข้าถึงได้จากภายนอก Module และใช้คีย์เวิร์ด import เพื่อนำเข้าโค้ดจาก Module อื่น

ตัวอย่างการสร้าง Module ใน TypeScript:

// File: utils.ts
export function formatDate(date: Date): string {
  // ...
}

export function generateId(): string {
  // ...
}

// File: app.ts
import { formatDate, generateId } from './utils';

const today = new Date();
console.log(formatDate(today));

const userId = generateId();
console.log(userId);

ในตัวอย่างนี้ เราสร้าง Module utils.ts ที่มีฟังก์ชัน formatDate() และ generateId() ซึ่งถูก export เพื่อให้สามารถใช้งานได้จากภายนอก Module จากนั้นในไฟล์ app.ts เราทำการ import ฟังก์ชันเหล่านั้นจาก Module utils.ts และนำมาใช้งาน

การใช้ Modules ช่วยให้เราสามารถแยกโค้ดออกเป็นส่วนๆ ที่มีหน้าที่เฉพาะ และนำส่วนต่างๆ มาประกอบกันเพื่อสร้างแอปพลิเคชันที่มีขนาดใหญ่และซับซ้อนได้ ทำให้โค้ดมีความเป็นมอดูลาร์ (Modular) ง่ายต่อการทำความเข้าใจ และง่ายต่อการบำรุงรักษา

การใช้ Classes และ Modules ใน TypeScript ช่วยให้นักพัฒนาสามารถสร้างโค้ดที่มีโครงสร้างที่ดี อ่านง่าย และง่ายต่อการบำรุงรักษา รวมถึงส่งเสริมการนำโค้ดกลับมาใช้ใหม่ได้อย่างมีประสิทธิภาพ ซึ่งเป็นประโยชน์อย่างมากในการพัฒนา Next.js App ที่มีขนาดใหญ่และต้องการการจัดการโค้ดที่ดี

Last updated