Dark mode
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;