TypeScript (TS) คือภาษาโปรแกรมที่พัฒนาโดย Microsoft เป็นซูเปอร์เซต (Superset) ของ JavaScript หมายความว่าโค้ด JavaScript ที่ถูกต้องทั้งหมดถือเป็นโค้ด TypeScript ที่ถูกต้องด้วย สิ่งที่ TypeScript เพิ่มเข้ามาคือระบบ Static Typing ที่เข้มงวด ทำให้สามารถตรวจจับข้อผิดพลาดในโค้ดได้ตั้งแต่ขั้นตอนการพัฒนา (Compile-Time) ก่อนที่โปรแกรมจะเริ่มทำงานจริง
เนื่องจากเบราว์เซอร์หรือ Node.js ยังไม่สามารถรันโค้ด TypeScript ได้โดยตรง จึงต้องมีการแปลง (Compile) โค้ด TS ให้เป็น JavaScript (JS) ก่อนใช้งาน
เราสามารถทดสอบโค้ดและรันคำสั่งภาษาโปรแกรม TypeScript ได้ผ่านเว็บไซต์
เริ่มต้น TypeScript Programming
ในโปรแกรม TypeScript การเริ่มต้นเขียนโค้ดจะคล้ายกับ JavaScript โดยสามารถเริ่มด้วยการใช้ฟังก์ชัน console.log() เพื่อแสดงข้อความ
// unction main() ไม่จำเป็น แต่ก็สามารถใช้ได้หากต้องการกำหนดขอบเขต
console.log('Hello, TypeScript World!');
ตัวแปร (Variables) และชนิดข้อมูล (Data Types)
TypeScript มีการกำหนดตัวแปรด้วยคำสั่ง var, let, และ const เหมือน JavaScript แต่จุดสำคัญคือความสามารถในการกำหนด ชนิดข้อมูล (Type Annotation) ให้กับตัวแปรอย่างชัดเจน
| ชนิดข้อมูลพื้นฐาน | ตัวอย่าง |
| string (ข้อความ) |
let name: string = 'Ninenik'; |
| number (ตัวเลข) |
let age: number = 24; |
| boolean (ตรรกะ) |
let isActive: boolean = true; |
| Array (รายการ) |
let hobby: string[] = ['Reading', 'Jogging']; |
| Tuple (อาร์เรย์ที่มีชนิดข้อมูลและจำนวนจำกัด) |
let position: [number, string] = [1, 'first']; |
| any (ยอมรับได้ทุกชนิด) |
let data: any = 'mixed data'; |
ตัวอย่างการกำหนดชนิดข้อมูล:
let name: string = 'Ebiwayo';
let age: number = 24;
let hobby: string[] = ['Reading', 'Jogging', 'Shopping'];
// การกำหนด Object จะใช้ Interface หรือ Type Alias
let address: { city: string[], country: string } = {
city: ['Bangkok'],
country: 'Thailand'
};
console.log(`Name type: ${typeof name}`);
console.log(`Age type: ${typeof age}`);
การควบคุมชุดคำสั่ง (Control Flow Statements)
รูปแบบการควบคุมการทำงานของโปรแกรมใน TypeScript ใช้รูปแบบชุดคำสั่งเดียวกับ Dart/JavaScript ทั่วไป เช่น การใช้งาน if/else, for loops, while/do-while loops, break/continue, และ switch/case
ตัวอย่างการควบคุม:
let age = 24;
let hobby: string[] = ['Reading', 'Jogging', 'Shopping'];
for (let i = 0; i < hobby.length; i++) {
console.log(hobby[i]);
}
if (age > 18) {
console.log('You are old enough.');
} else {
console.log('Still young.');
}
ฟังก์ชัน (Functions)
สำหรับการใช้งานฟังก์ชันใน TypeScript เราสามารถ (และควร) กำหนดชนิดข้อมูลของ Arguments (พารามิเตอร์) และ Return Type (ชนิดข้อมูลที่คืนค่า) เพื่อเพิ่มความปลอดภัยของโค้ด
ตัวอย่างฟังก์ชันที่มีการกำหนดชนิดข้อมูล:
// สร้างฟังก์ชันหาปี พ.ศ. เกิดจาก อายุ
function yearBorned(age: number): number {
const currentYear = new Date().getFullYear();
// คืนค่าเป็นปี พ.ศ. (ปี ค.ศ. + 543)
return (currentYear - age) + 543;
}
let name: string = 'Ebiwayo';
let age: number = 24;
let bornedYear = yearBorned(age);
console.log(`${name} เกิดปี พ.ศ. ${bornedYear}`);
// ผลลัพธ์: Ebiwayo เกิดปี พ.ศ. 25XX
การคอมเมนต์ (Comments)
การคอมเมนต์หรือปิดการทำงานของโค้ดบางส่วนใช้รูปแบบเดียวกับภาษา Dart/JavaScript:
-
Single-line: ใช้
//ไว้หน้าบรรทัด -
Multi-line: ใช้
/*เปิด และ*/ปิด สำหรับการคอมเมนต์หลายบรรทัด
การจัดการโมดูล (Imports/Exports)
TypeScript ใช้ระบบโมดูล (Module) ของ ES6 ในการนำเข้าและส่งออกโค้ดจากไฟล์อื่น โดยใช้คำสั่ง import และ export
// ไฟล์ math.ts
export const PI = 3.14159;
export function calculate(a: number): number {
return a * 2;
}
// ไฟล์หลัก index.ts
import { PI, calculate } from './math';
// import * as MathUtils from './math'; // การ import พร้อมกำหนดชื่ออ้างอิง
console.log(PI); // แสดงค่า PI
// console.log(MathUtils.PI); // หากใช้การ import แบบ * as
คลาส (Classes)
การกำหนด class เป็นรูปแบบการเขียนโปรแกรมเชิงวัตถุ (OOP) ใน TypeScript ซึ่งรองรับคุณสมบัติเต็มรูปแบบของ OOP รวมถึงการกำหนดตัวสร้าง (Constructor) และเมธอด (Method)
ตัวอย่าง Class เบื้องต้น:
class Rectangle {
// กำหนด Property และชนิดข้อมูล
private width: number;
private height: number;
// Constructor: กำหนดตัวสร้างเมื่อมีการสร้าง Object
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
// Method: ฟังก์ชันสำหรับการหาพื้นที่
public area(): number {
return this.width * this.height;
}
}
// ทดสอบใช้งาน Rectangle class
let myRect = new Rectangle(100, 50);
console.log(myRect.area()); // 5000
อินเทอร์เฟซ (Interfaces) และ Abstract Class
Interfaces
TypeScript ใช้คีย์เวิร์ด interface ในการกำหนดโครงสร้าง (Contract) ของ Object อย่างชัดเจน ต่างจาก Dart ที่ทุกคลาสเป็น Interface โดยปริยาย Interface เป็นคุณสมบัติที่สำคัญมากใน TypeScript
interface Shape {
width: number;
height: number;
area(): number;
perimeter(): number;
}
class Square implements Shape {
width: number;
height: number;
constructor(size: number) {
this.width = size;
this.height = size;
}
area(): number {
return this.width * this.height;
}
perimeter(): number {
return this.width * 4;
}
}
Abstract Class
abstract class ใช้เพื่อกำหนดคลาสที่เป็นพิมพ์เขียวโดยตรง ซึ่งไม่สามารถสร้างเป็น Object ได้เอง และต้องมีคลาสลูก (Child Class) มาสืบทอด (Extend) เท่านั้น มักใช้ร่วมกับ abstract method ที่ต้องถูก Override ในคลาสลูก
การสืบทอด (Inheritance)
การสืบทอดใช้คีย์เวิร์ด extends เพื่อให้คลาสลูกสามารถนำ Property และ Method จากคลาสแม่ (Parent Class) มาใช้ซ้ำได้ โดยใช้ super เพื่ออ้างถึง Method ของคลาสแม่
class Tv {
turnOn() {
console.log("Illuminate Display");
console.log("Activate IR Sensor");
}
}
// สืบทอด class ย่อยด้วยการ extends จาก parent class
class SmartTv extends Tv {
turnOn() {
super.turnOn(); // เรียกใช้ method ของ parent class
console.log("Boot Network Interface");
console.log("Initialize Memory");
}
}
new Tv().turnOn();
// Output: Illuminate Display, Activate IR Sensor
new SmartTv().turnOn();
// Output: Illuminate Display, Activate IR Sensor, Boot Network Interface, Initialize Memory
การทำงานแบบอะซิงโครนัส (Asynchronous Programming)
TypeScript (และ JavaScript ยุคใหม่) จัดการกับการดำเนินการแบบ Asynchronous (เช่น การเรียกข้อมูลจาก API, การอ่านไฟล์) โดยใช้ Promises, async, และ await เพื่อให้โค้ดมีความอ่านง่ายและทำงานแบบ Non-blocking
ตัวอย่าง Async/Await:
// ฟังก์ชันจำลองการดึงข้อมูลที่ใช้เวลา 1 วินาที และคืนค่าเป็น Promise<string>
function getUserOrder(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Big Mac and Fries');
}, 1000);
});
}
// ฟังก์ชันหลักที่ใช้ async/await
async function createOrderMessage(): Promise<string> {
try {
// await ทำให้โค้ดหยุดรอจนกว่า Promise จะเสร็จสมบูรณ์ (เหมือนกับการทำงานแบบ Synchronous)
const order = await getUserOrder();
return `Your order is: ${order}`;
} catch (error) {
return 'Could not retrieve order.';
}
}
// เรียกใช้งาน
createOrderMessage().then(message => {
console.log(message);
// ผลลัพธ์จะปรากฏหลังจากผ่านไป 1 วินาที
});