TypeScript Tips: 10 เทคนิคที่จะทำให้โค้ดของคุณดีขึ้น
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 ของคุณปลอดภัยและอ่านง่ายขึ้นมาก ลองนำไปใช้ในโปรเจกต์จริงดูครับ
ความคิดเห็น
กำลังโหลดความคิดเห็น...
บทความที่เกี่ยวข้อง
การจัดการ State ใน React: จาก useState สู่ Zustand
เข้าใจ state management ใน React ตั้งแต่ useState, Context API จนถึง Zustand ว่าควรใช้ตัวไหนเมื่อไหร่
Programming
1 นาทีอ่าน
วิธีเรียนรู้ภาษาโปรแกรมใหม่อย่างมีประสิทธิภาพ
แชร์ 7 ขั้นตอนในการเรียนรู้ภาษาโปรแกรมใหม่อย่างมีประสิทธิภาพ จากประสบการณ์ที่เรียนมากกว่า 5 ภาษา
Programming
1 นาทีอ่าน
API Design: หลักการออกแบบ REST API ที่ดี
รวมหลักการออกแบบ REST API ที่ดี ตั้งแต่ naming convention, HTTP methods, error handling จนถึง versioning
Programming
1 นาทีอ่าน