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
แจ้งเตือนก่อนรัน"]
npm install -g typescript
tsc --init
| 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`);
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 User {
readonly id: number;
name: string;
age?: number;
}
const user: User = {
id: 1,
name: "Ana"
};
console.log(user.name);
type Point = {
x: number;
y: number;
};
const point: Point = { x: 10, y: 20 };
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);
โดยที่ C คือเปอร์เซ็นต์ type coverage, typed คือจำนวนส่วนที่ระบุ type แล้ว, และ total คือจำนวนส่วนทั้งหมด
any และ unknown ต่างกันอย่างไร