REFERENSI CEPAT TYPESCRIPT
Type, interface, generics, utility type
Tipe Dasar
Primitif
let name: string = "Alice";
let age: number = 25;
let active: boolean = true;
let data: null = null;
let x: undefined = undefined;
Tipe Khusus
| any | Nonaktifkan pengecekan tipe |
| unknown | any yang type-safe (harus di-narrow sebelum dipakai) |
| void | Tidak ada return value |
| never | Fungsi tidak pernah kembali (throw / infinite) |
| object | Tipe non-primitif apa pun |
Array & Tuple
Array
let nums: number[] = [1, 2, 3];
let names: Array = ["a", "b"];
let matrix: number[][] = [[1, 2], [3, 4]];
Tuple
let pair: [string, number] = ["age", 25];
let rgb: [number, number, number] = [255, 0, 0];
// Named tuples (labels for readability)
type Point = [x: number, y: number];
Interface
Mendefinisikan & Menggunakan
interface User {
name: string;
age: number;
email?: string; // optional
readonly id: number; // immutable
}
const user: User = { name: "Alice", age: 25, id: 1 };
Memperluas Interface
interface Employee extends User {
role: string;
department: string;
}
Index Signature
interface StringMap {
[key: string]: string;
}
const env: StringMap = { NODE_ENV: "prod" };
Type Alias
type ID = string | number;
type Point = { x: number; y: number };
type Callback = (data: string) => void;
Interface vs Type
| interface | Bisa di-extend dengan extends, mendukung declaration merging |
| type | Union, intersection, mapped type, tuple |
Union & Intersection
Union Type
type Status = "loading" | "success" | "error";
type ID = string | number;
function print(val: string | number) {
if (typeof val === "string") {
console.log(val.toUpperCase());
}
}
Intersection Type
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
// Person has both name and age
Discriminated Union
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; w: number; h: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "rect": return s.w * s.h;
}
}
Fungsi
Parameter & Return Bertipe
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const greet = (name: string): string =>
`Hello, ${name}!`;
// Optional & default params
function log(msg: string, level?: string): void {}
function log(msg: string, level = "info"): void {}
Function Overload
function parse(input: string): number;
function parse(input: number): string;
function parse(input: string | number) {
return typeof input === "string"
? parseInt(input)
: input.toString();
}
Rest Parameter
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
Generics
Fungsi Generic
function identity(value: T): T {
return value;
}
identity("hello"); // explicit
identity(42); // inferred: number
Interface Generic & Constraint
interface Box {
value: T;
}
const box: Box = { value: 42 };
// Constraints
function getLen(
item: T
): number {
return item.length;
}
Enum
enum Direction { Up, Down, Left, Right }
let d: Direction = Direction.Up; // 0
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
}
let s: Status = Status.Active; // "ACTIVE"
// const enum (inlined at compile time)
const enum Color { Red, Green, Blue }
Type Guard
Guard Bawaan
// typeof
if (typeof x === "string") { /* x: string */ }
// instanceof
if (err instanceof Error) { /* err: Error */ }
// in
if ("name" in obj) { /* obj has name */ }
Custom Type Guard
function isString(val: unknown): val is string {
return typeof val === "string";
}
if (isString(input)) {
input.toUpperCase(); // narrowed to string
}
Assertion Function
function assertDefined(
val: T | null
): asserts val is T {
if (val === null) throw new Error("null");
}
Utility Type
| Partial<T> | Semua properti opsional |
| Required<T> | Semua properti wajib |
| Readonly<T> | Semua properti readonly |
| Pick<T, K> | Pilih properti K dari T |
| Omit<T, K> | Hapus properti K dari T |
| Record<K, V> | Objek dengan key K dan value V |
| Exclude<T, U> | Tipe di T yang tidak ada di U |
| Extract<T, U> | Tipe di T yang juga ada di U |
| NonNullable<T> | Hapus null dan undefined dari T |
| ReturnType<T> | Tipe return fungsi T |
| Parameters<T> | Tipe parameter fungsi T |
| Awaited<T> | Buka tipe Promise |
Contoh Utility Type
interface User { name: string; age: number; email: string }
type UserPreview = Pick;
type UserUpdate = Partial;
type UserMap = Record;
type CreateUser = Omit;