Catatan Belajar TypeScript: Dari Dasar hingga Advanced
Dokumentasi perjalanan belajar TypeScript, mulai dari konsep dasar type system hingga fitur advanced seperti generics, utility types, dan conditional types.
Mengapa TypeScript?
TypeScript menambahkan type safety ke JavaScript, yang membantu kita menangkap bug lebih awal, sebelum kode berjalan di production.
Basic Types
// Primitive types
const name: string = 'Wawan';
const age: number = 28;
const isActive: boolean = true;
// Arrays
const numbers: number[] = [1, 2, 3];
const names: Array<string> = ['Alice', 'Bob'];
// Tuple
const pair: [string, number] = ['age', 28];
Interface vs Type
Keduanya mirip, tapi ada perbedaan penting:
// Interface — dapat di-extend dan merge
interface User {
name: string;
email: string;
}
interface Admin extends User {
role: 'admin' | 'superadmin';
}
// Type — lebih fleksibel untuk union dan intersection
type Status = 'active' | 'inactive' | 'pending';
type UserOrAdmin = User | Admin;
Generics
Membuat fungsi dan class yang reusable:
function getFirst<T>(arr: T[]): T | undefined {
return arr[0];
}
const firstNum = getFirst([1, 2, 3]); // type: number
const firstName = getFirst(['a', 'b']); // type: string
Utility Types
TypeScript menyediakan utility types bawaan:
interface Post {
title: string;
content: string;
author: string;
published: boolean;
}
// Semua field jadi optional
type PostDraft = Partial<Post>;
// Semua field jadi required
type RequiredPost = Required<Post>;
// Ambil sebagian field
type PostPreview = Pick<Post, 'title' | 'author'>;
// Hilangkan sebagian field
type PostWithoutContent = Omit<Post, 'content'>;
// Read-only
type ReadonlyPost = Readonly<Post>;
Conditional Types
Type yang berubah berdasarkan kondisi:
type IsString<T> = T extends string ? 'yes' : 'no';
type A = IsString<string>; // 'yes'
type B = IsString<number>; // 'no'
Discriminated Unions
Pattern yang sangat berguna untuk state management:
type State =
| { status: 'loading' }
| { status: 'success'; data: string[] }
| { status: 'error'; message: string };
function handleState(state: State) {
switch (state.status) {
case 'loading':
return 'Loading...';
case 'success':
return state.data.join(', '); // TypeScript tahu 'data' ada
case 'error':
return `Error: ${state.message}`; // TypeScript tahu 'message' ada
}
}
Kesimpulan
TypeScript bukan hanya tentang menambah type, tapi tentang mendokumentasikan intent dan mengurangi cognitive load saat membaca kode.
Catatan ini akan terus saya update seiring perjalanan belajar. Stay tuned! 📝