ข้ามไปยังเนื้อหาหลัก
TypeScript Tips: 10 เทคนิคที่จะทำให้โค้ดของคุณดีขึ้น

TypeScript Tips: 10 เทคนิคที่จะทำให้โค้ดของคุณดีขึ้น

· 1 นาทีในการอ่าน · Programming
TypeScriptJavaScriptProgramming Tips

TypeScript มี features มากมายที่ช่วยให้โค้ดปลอดภัยขึ้น มาดูเทคนิคที่น่าสนใจกัน

1. Utility Types

Partial, Pick, Omit เป็น utility types ที่ใช้บ่อยมาก:

typescript
interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

// Partial - ทำให้ทุก property เป็น optional
type UpdateUser = Partial<User>;

// Pick - เลือกเฉพาะ property ที่ต้องการ
type UserPreview = Pick<User, 'id' | 'name'>;

// Omit - ตัด property ที่ไม่ต้องการ
type CreateUser = Omit<User, 'id'>;

2. Type Guards

ใช้ type guard เพื่อ narrow type ใน runtime:

typescript
function isString(value: unknown): value is string {
  return typeof value === 'string';
}

function processValue(value: unknown) {
  if (isString(value)) {
    // TypeScript รู้ว่า value เป็น string แล้ว
    console.log(value.toUpperCase());
  }
}

3. Const Assertions

typescript
// ปกติ TypeScript infer เป็น string[]
const colors = ['red', 'blue', 'green'];

// ใช้ as const จะได้ readonly tuple
const colors2 = ['red', 'blue', 'green'] as const;
// type: readonly ['red', 'blue', 'green']

// ใช้กับ object ก็ได้
const config = {
  api: 'https://api.example.com',
  timeout: 5000,
} as const;

4. Template Literal Types

typescript
type Color = 'red' | 'blue' | 'green';
type Size = 'sm' | 'md' | 'lg';

// สร้าง type จาก combination
type ClassName = `${Size}-${Color}`;
// 'sm-red' | 'sm-blue' | 'sm-green' | 'md-red' | ...

เทคนิคเหล่านี้จะช่วยให้โค้ด TypeScript ของคุณปลอดภัยและอ่านง่ายขึ้นมาก ลองนำไปใช้ในโปรเจกต์จริงดูครับ

แชร์:

ความคิดเห็น

กำลังโหลดความคิดเห็น...

บทความที่เกี่ยวข้อง