Dark mode
Basic Types (ประเภทข้อมูลพื้นฐาน)
ประเภทข้อมูลพื้นฐานใน TypeScript ที่ใช้บ่อยที่สุด พร้อมตัวอย่างการใช้งานจริง
Primitive Types (ประเภทพื้นฐาน)
ประเภทข้อมูลพื้นฐานที่สำคัญใน TypeScript:
number
ใช้สำหรับตัวเลขทุกประเภท ทั้งจำนวนเต็มและทศนิยม
ts
// ตัวอย่างการใช้งาน
let age: number = 30; // จำนวนเต็ม
let price: number = 99.99; // ทศนิยม
let hex: number = 0xf00d; // เลขฐานสิบหก
let binary: number = 0b1010; // เลขฐานสอง
// ใช้งานกับคณิตศาสตร์
function calculateTax(amount: number, rate: number): number {
return amount * (rate / 100);
}
const tax = calculateTax(1000, 7); // ได้ 70
string
ใช้สำหรับข้อความและเนื้อความต่างๆ
ts
let firstName: string = "John";
let lastName: string = "Doe";
let fullName: string = `${firstName} ${lastName}`; // Template literal
// ตัวอย่างการใช้งานจริง
function greet(name: string): string {
return `Hello, ${name}!`;
}
const greeting = greet(fullName); // "Hello, John Doe!"
boolean
ใช้สำหรับค่าทางตรรกะ (จริง/เท็จ)
ts
let isActive: boolean = true;
let hasPermission: boolean = false;
// ใช้งานกับเงื่อนไข
function checkAccess(userRole: string): boolean {
return userRole === "admin";
}
const canEdit = checkAccess("editor"); // false
null และ undefined
ts
let emptyValue: null = null;
let notDefined: undefined = undefined;
Object Types (ประเภทอ็อบเจกต์)
Interface
ใช้กำหนดโครงสร้างของอ็อบเจกต์
ts
interface Product {
id: number;
name: string;
price: number;
inStock?: boolean; // Optional property
readonly createdAt: Date; // ไม่สามารถแก้ไขค่าได้
}
const laptop: Product = {
id: 1,
name: "MacBook Pro",
price: 45000,
createdAt: new Date(),
};
// laptop.createdAt = new Date(); // Error เพราะเป็น readonly
Type Aliases
ทางเลือกแทน interface สำหรับกำหนดประเภท
ts
type Point = {
x: number;
y: number;
};
const center: Point = {
x: 0,
y: 0,
};
Collection Types (ประเภทชุดข้อมูล)
Array
ts
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["John", "Jane"]; // Generic syntax
// ใช้งานกับฟังก์ชัน
function sum(numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
Tuple
อาร์เรย์ที่กำหนดประเภทและลำดับของสมาชิก
ts
let person: [string, number] = ["John", 30];
// ตัวอย่างการใช้งานกับ React useState
const [count, setCount] = useState<number>(0);
Enum
ts
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
let move: Direction = Direction.Up;
Special Types (ประเภทพิเศษ)
any
ใช้เมื่อต้องการเลี่ยงการตรวจสอบประเภท
ts
let flexible: any = 4;
flexible = "could be a string";
flexible = false; // เปลี่ยนประเภทได้
flexible.toUpperCase(); // ใช้งานได้แต่เสี่ยง error runtime
// ควรใช้เฉพาะเมื่อจำเป็น เช่น ทำงานกับไลบรารีภายนอก
unknown
ปลอดภัยกว่า any ต้องตรวจสอบประเภทก่อนใช้งาน
ts
let notSure: unknown = 4;
notSure = "maybe a string";
if (typeof notSure === "string") {
// ภายในบล็อกนี้ TypeScript รู้ว่า notSure เป็น string
console.log(notSure.toUpperCase());
}
void
ใช้กับฟังก์ชันที่ไม่คืนค่า
ts
function logMessage(message: string): void {
console.log(message);
// ไม่มี return statement
}
// ใช้กับ callback function
setTimeout((): void => {
console.log("Done!");
}, 1000);
never
ใช้กับฟังก์ชันที่ไม่มีทางทำงานสำเร็จ
ts
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}
// ใช้งานกับ exhaustive checking
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
Complex Types (ประเภทเชิงซ้อน)
Array
ts
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"]; // Generic syntax
// ใช้งานกับฟังก์ชัน
function sum(numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
Tuple
ts
let person: [string, number] = ["John", 30];
// ใช้งานกับ React useState
const [count, setCount] = useState<number>(0);
Enum
ts
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
function move(direction: Direction) {
// ...
}
move(Direction.Up);
Type Checking (การตรวจสอบประเภท)
ts
// typeof type guard
if (typeof variable === "string") {
// ภายในนี้ variable เป็น string
}
// instanceof type guard
if (error instanceof Error) {
// ภายในนี้ error เป็น Error
}