TS DOCS

BASIC-TYPES

string
Description: Tipe data teks.
Example:
let name: string = 'Ridho'
Output: Type: string
number
Description: Tipe data angka (integer, float, hex, octal, binary).
Example:
let age: number = 25
Output: Type: number
boolean
Description: Tipe data true/false.
Example:
let isActive: boolean = true
Output: Type: boolean
null
Description: Tipe null (biasanya dengan strictNullChecks).
Example:
let nothing: null = null
Output: Type: null
undefined
Description: Tipe undefined.
Example:
let notDefined: undefined = undefined
Output: Type: undefined
any
Description: Nonaktifkan type checking (hindari jika bisa).
Example:
let data: any = 123; data = 'hello'
Output: No error
unknown
Description: Tipe aman untuk nilai yang tidak diketahui.
Example:
let input: unknown = 'hello'; (input as string).toUpperCase()
Output: Perlu type assertion
void
Description: Fungsi tidak mengembalikan nilai.
Example:
function log(msg: string): void { console.log(msg) }
Output: No return
never
Description: Fungsi tidak pernah selesai (throw error atau infinite loop).
Example:
function error(msg: string): never { throw new Error(msg) }
Output: Never
array
Description: Array dengan tipe elemen tertentu.
Example:
let list: number[] = [1, 2, 3]
Output: Type: number[]
tuple
Description: Array dengan jumlah dan tipe elemen tetap.
Example:
let pair: [string, number] = ['age', 25]
Output: Type: [string, number]
enum
Description: Enum numerik atau string (gunakan const enum untuk optimasi).
Example:
enum Color { Red, Green, Blue }
Output: Color.Red = 0
literal type
Description: Tipe yang hanya menerima nilai literal tertentu.
Example:
let direction: 'left' | 'right' = 'left'
Output: Union literal
union type
Description: Gabungan beberapa tipe.
Example:
let id: string | number = 123
Output: Bisa string atau number
intersection type
Description: Gabungan semua properti dari beberapa tipe.
Example:
type A = { a: number } & { b: string }
Output: { a: number, b: string }
object
Description: Tipe objek umum.
Example:
let user: object = { name: 'Ridho' }
Output: Type: object (tidak spesifik)
symbol
Description: Tipe data simbol (unik).
Example:
let sym: symbol = Symbol('key')
Output: Type: symbol
bigint
Description: Tipe bilangan besar.
Example:
let big: bigint = 9007199254740991n
Output: Type: bigint
nullish coalescing
Description: Operator ?? untuk memberikan nilai default jika null/undefined.
Example:
let x = foo ?? 'default'
Output: x = 'default' jika foo null/undefined
optional chaining
Description: Akses properti dalam dengan aman (?. ).
Example:
let street = user?.address?.street
Output: undefined jika tidak ada

INTERFACES-TYPES

interface
Description: Mendefinisikan kontrak objek (bisa di-extend).
Example:
interface User { name: string; age: number }
Output: User type
extending interface
Description: Pewarisan interface.
Example:
interface Admin extends User { role: string }
Output: Admin memiliki name, age, role
type alias
Description: Alias tipe untuk tipe apa pun.
Example:
type Point = { x: number; y: number }
Output: Point type
type vs interface
Description: Interface bisa di-merge deklarasi, type bisa union/intersection.
Example:
type ID = string | number
Output: Union type
readonly
Description: Properti tidak bisa diubah setelah inisialisasi.
Example:
interface Config { readonly apiKey: string }
Output: Tidak bisa reassign
optional properties
Description: Properti dengan ? tidak wajib.
Example:
interface User { name: string; age?: number }
Output: age opsional
index signatures
Description: Properti dengan key dinamis.
Example:
interface Dict { [key: string]: number }
Output: Semua key string -> number
call signature
Description: Tipe untuk fungsi.
Example:
interface Fn { (x: number): string }
Output: Fungsi dengan signature
construct signature
Description: Tipe untuk constructor.
Example:
interface Ctor { new (x: number): Date }
Output: Constructor
hybrid type
Description: Objek yang juga bisa dipanggil.
Example:
interface Counter { (): number; count: number }
Output: Fungsi + properti

GENERICS

generic function
Description: Fungsi dengan parameter tipe.
Example:
function identity<T>(arg: T): T { return arg }
Output: identity<string>('hello')
generic interface
Description: Interface dengan tipe generik.
Example:
interface Box<T> { value: T }
Output: Box<string>
generic constraints
Description: Batasi tipe generik dengan extends.
Example:
function getLength<T extends { length: number }>(arg: T): number { return arg.length }
Output: Terima yang punya .length
generic default
Description: Nilai default parameter tipe.
Example:
interface Page<T = string> { data: T }
Output: Default string
keyof with generics
Description: Ambil key dari tipe.
Example:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key] }
Output: Akses properti aman
generic class
Description: Kelas dengan tipe generik.
Example:
class Repository<T> { items: T[] = [] }
Output: Repository<User>
infer keyword
Description: Ambil tipe dalam conditional type.
Example:
type Return<T> = T extends (...args: any[]) => infer R ? R : never
Output: ReturnType buatan
const type parameters (TS 5.0)
Description: Parameter tipe dengan const modifier.
Example:
function getConst<T, const T2>(a: T, b: T2) {}
Output: Literal type lebih presisi

UTILITY-TYPES

Partial<T>
Description: Semua properti jadi opsional.
Example:
Partial<{ a: number; b: string }>
Output: { a?: number; b?: string }
Required<T>
Description: Semua properti jadi wajib.
Example:
Required<{ a?: number }>
Output: { a: number }
Readonly<T>
Description: Semua properti readonly.
Example:
Readonly<{ a: number }>
Output: { readonly a: number }
Record<K, T>
Description: Objek dengan key K dan value T.
Example:
Record<'a' | 'b', number>
Output: { a: number; b: number }
Pick<T, K>
Description: Ambil subset properti.
Example:
Pick<{ a: number; b: string }, 'a'>
Output: { a: number }
Omit<T, K>
Description: Buang subset properti.
Example:
Omit<{ a: number; b: string }, 'b'>
Output: { a: number }
Exclude<T, U>
Description: Keluarkan tipe yang ada di U dari T.
Example:
Exclude<'a' | 'b' | 'c', 'a'>
Output: 'b' | 'c'
Extract<T, U>
Description: Ambil tipe yang ada di U dari T.
Example:
Extract<'a' | 'b', 'a' | 'c'>
Output: 'a'
NonNullable<T>
Description: Buang null dan undefined.
Example:
NonNullable<string | null | undefined>
Output: string
ReturnType<T>
Description: Ambil tipe return fungsi.
Example:
ReturnType<() => string>
Output: string
Parameters<T>
Description: Ambil tipe parameter fungsi sebagai tuple.
Example:
Parameters<(a: number, b: string) => void>
Output: [number, string]
ConstructorParameters<T>
Description: Ambil parameter constructor.
Example:
ConstructorParameters<typeof Date>
Output: [string | number | Date]
InstanceType<T>
Description: Ambil tipe instance dari constructor.
Example:
InstanceType<typeof Date>
Output: Date
Awaited<T>
Description: Unwrap Promise.
Example:
Awaited<Promise<string>>
Output: string
Uppercase<StringType>
Description: Ubah string literal ke uppercase.
Example:
Uppercase<'hello'>
Output: 'HELLO'
Lowercase<StringType>
Description: Ubah ke lowercase.
Example:
Lowercase<'HELLO'>
Output: 'hello'
Capitalize<StringType>
Description: Kapitalisasi huruf pertama.
Example:
Capitalize<'hello'>
Output: 'Hello'
Uncapitalize<StringType>
Description: Uncapitalize huruf pertama.
Example:
Uncapitalize<'Hello'>
Output: 'hello'

TYPE-MANIPULATION

keyof T
Description: Union key dari T.
Example:
type Keys = keyof { a: number; b: string }
Output: 'a' | 'b'
typeof
Description: Ambil tipe dari nilai/variabel.
Example:
let user = { name: 'Ridho' }; type UserType = typeof user
Output: { name: string }
T[K] (indexed access)
Description: Akses tipe properti.
Example:
type NameType = User['name']
Output: string
conditional types
Description: Tipe kondisional T extends U ? X : Y.
Example:
type IsString<T> = T extends string ? true : false
Output: IsString<'hello'> = true
distributive conditional
Description: Kondisional terdistribusi pada union.
Example:
type ToArray<T> = T extends any ? T[] : never
Output: ToArray<string|number> = string[] | number[]
mapped types
Description: Iterasi key untuk membuat tipe baru.
Example:
type Readonly<T> = { readonly [K in keyof T]: T[K] }
Output: Custom utility
key remapping (as)
Description: Ganti key dalam mapped type.
Example:
type Getters<T> = { [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K] }
Output: Mengubah nama key
template literal types
Description: Gabung string literal.
Example:
type Greeting = `Hello, ${string}!`
Output: Semua string dengan prefix 'Hello, ' dan suffix '!'
infer in conditional
Description: Ekstrak sub-tipe.
Example:
type Unpack<T> = T extends (infer U)[] ? U : T
Output: Unpack<number[]> = number
assertion functions
Description: Fungsi yang meyakinkan TS tentang tipe.
Example:
function assert(condition: any, msg?: string): asserts condition
Output: Type guard
const assertions (as const)
Description: Buat literal readonly dan narrow.
Example:
let arr = [1, 2, 3] as const
Output: readonly [1, 2, 3]
satisfies operator
Description: Validasi tipe tanpa memperluas tipe.
Example:
let x = { a: 1 } satisfies Record<string, number>
Output: Tetap { a: number }
typeof import
Description: Ambil tipe dari module yang diimport.
Example:
type MyModule = typeof import('./module')
Output: Tipe modul

NARROWING-GUARDS

typeof guard
Description: Narrowing dengan typeof.
Example:
if (typeof x === 'string') { x.toUpperCase() }
Output: x jadi string
instanceof guard
Description: Narrowing dengan instanceof.
Example:
if (x instanceof Date) { x.getFullYear() }
Output: x jadi Date
in operator
Description: Cek keberadaan properti.
Example:
if ('name' in obj) { obj.name }
Output: Tipe narrowed
custom type guard
Description: Fungsi dengan return type predicate.
Example:
function isString(val: unknown): val is string { return typeof val === 'string' }
Output: val is string
discriminated union
Description: Union dengan properti literal pembeda.
Example:
type Shape = { kind: 'circle'; radius: number } | { kind: 'rect'; width: number }
Output: Switch pada kind
exhaustiveness check
Description: never untuk memastikan semua kasus ditangani.
Example:
default: const _exhaustive: never = shape
Output: Error jika ada union baru
truthiness narrowing
Description: Menggunakan truthy/falsy.
Example:
if (value) { /* value bukan null/undefined */ }
Output: Narrowing

MODULES-NAMESPACES

ESM import/export
Description: Sintaks module modern.
Example:
import { fn } from './module'
Output: ES module
default import/export
Description: Import/export default.
Example:
import express from 'express'
Output: Default
type import
Description: Hanya import tipe (dihapus saat kompilasi).
Example:
import type { User } from './types'
Output: Type-only import
import type dengan inline
Description: Import sebagian tipe.
Example:
import { type User, helper } from './module'
Output: User adalah tipe
namespace (ambient/module)
Description: Namespace lama, hindari jika bisa.
Example:
namespace MyApp { export interface Config {} }
Output: Digantikan ES modules
declare module
Description: Deklarasikan tipe untuk modul eksternal.
Example:
declare module '*.svg' { const content: string; export default content }
Output: Import SVG
global declaration
Description: Perluas tipe global (Window, dll).
Example:
declare global { interface Window { myProp: string } }
Output: Window.myProp
moduleResolution
Description: Strategi resolusi modul (node16, bundler).
Example:
"moduleResolution": "bundler"
Output: tsconfig

DECORATORS

Class Decorator (Stage 3)
Description: Decorator pada class (tidak perlu experimental).
Example:
@sealed class MyClass {}
Output: Decorator
Method Decorator
Description: Decorator pada method.
Example:
@log class A { @log greet() {} }
Output: Logging
Accessor Decorator
Description: Decorator pada getter/setter.
Example:
@configurable get name() {}
Output: Accessor
Field Decorator
Description: Decorator pada field.
Example:
@required name: string
Output: Field
Decorator Context
Description: Parameter kedua decorator: ClassMethodDecoratorContext.
Example:
function log(target: any, context: ClassMethodDecoratorContext) {}
Output: Context metadata

ENUMS

Numeric enum
Description: Enum dengan nilai numerik auto-increment.
Example:
enum Direction { Up, Down }
Output: Direction.Up = 0
String enum
Description: Enum dengan nilai string.
Example:
enum Color { Red = 'RED', Green = 'GREEN' }
Output: Color.Red = 'RED'
const enum
Description: Enum yang dihapus saat kompilasi, nilai inline.
Example:
const enum Size { Small, Large }
Output: Tidak ada objek runtime
const assertions for enums
Description: Alternatif enum pakai as const.
Example:
const Colors = { Red: 'RED', Green: 'GREEN' } as const
Output: Readonly object

TSCONFIG

compilerOptions
Description: Opsi utama compiler TS.
Example:
"compilerOptions": { "target": "ES2022" }
Output: Target ES2022
target
Description: Versi JavaScript output.
Example:
"target": "ESNext"
Output: ES terbaru
module
Description: Sistem modul (ESNext, Node16, CommonJS).
Example:
"module": "Node16"
Output: Node16
moduleResolution
Description: Cara resolve modul (bundler, node16, classic).
Example:
"moduleResolution": "bundler"
Output: Bundler (Next.js)
strict
Description: Aktifkan semua strict checks.
Example:
"strict": true
Output: Semua ketat
strictNullChecks
Description: Null dan undefined tidak bisa diberikan ke tipe lain.
Example:
"strictNullChecks": true
Output: null tidak masuk string
noUncheckedIndexedAccess
Description: Indexed access menghasilkan undefined opsional.
Example:
"noUncheckedIndexedAccess": true
Output: arr[0] mungkin undefined
paths
Description: Path aliases untuk import.
Example:
"paths": { "@/*": ["./src/*"] }
Output: import dari @/
baseUrl
Description: Direktori dasar untuk resolve non-relatif.
Example:
"baseUrl": "./src"
Output: Resolve dari src
include
Description: File yang di-include.
Example:
"include": ["src/**/*"]
Output: Include src
exclude
Description: File yang dikecualikan.
Example:
"exclude": ["node_modules", "dist"]
Output: Exclude
outDir
Description: Folder output hasil kompilasi.
Example:
"outDir": "./dist"
Output: Output ke dist
declaration
Description: Generate file .d.ts.
Example:
"declaration": true
Output: File deklarasi
declarationMap
Description: Generate source map untuk deklarasi.
Example:
"declarationMap": true
Output: Navigasi ke source
sourceMap
Description: Generate .map untuk debugging.
Example:
"sourceMap": true
Output: Debug di TS
lib
Description: Library yang disertakan (DOM, ESNext).
Example:
"lib": ["ES2022", "DOM"]
Output: ES2022 + DOM
isolatedModules
Description: Pastikan setiap file bisa transpile sendiri (wajib Next.js).
Example:
"isolatedModules": true
Output: Wajib untuk bundler
forceConsistentCasingInFileNames
Description: Pastikan casing file konsisten.
Example:
"forceConsistentCasingInFileNames": true
Output: Error jika salah casing
skipLibCheck
Description: Lewati pengecekan tipe di .d.ts.
Example:
"skipLibCheck": true
Output: Cepat
noEmit
Description: Jangan emit output JS.
Example:
"noEmit": true
Output: Hanya cek tipe
esModuleInterop
Description: Interoperabilitas CommonJS.
Example:
"esModuleInterop": true
Output: Import default
resolveJsonModule
Description: Izinkan import JSON.
Example:
"resolveJsonModule": true
Output: Import json
allowImportingTsExtensions
Description: Izinkan .ts di import path.
Example:
"allowImportingTsExtensions": true
Output: Import './file.ts'

REACT-TYPES

React.FC
Description: Functional component dengan children opsional.
Example:
const Comp: React.FC<Props> = ({ children }) => <div>{children}</div>
Output: Component
React.ReactNode
Description: Semua yang bisa dirender (string, element, array, dll).
Example:
type Props = { children: React.ReactNode }
Output: Tipe children umum
React.ReactElement
Description: Hanya JSX element.
Example:
type Props = { element: React.ReactElement }
Output: JSX element
React.CSSProperties
Description: Tipe untuk style inline.
Example:
const style: React.CSSProperties = { color: 'red' }
Output: Style object
React.ComponentProps
Description: Ambil props dari komponen.
Example:
type BtnProps = React.ComponentProps<'button'>
Output: Semua atribut button
React.HTMLAttributes
Description: Atribut HTML generik.
Example:
type DivProps = React.HTMLAttributes<HTMLDivElement>
Output: Div attributes
React.FormEvent
Description: Event form.
Example:
onSubmit: (e: React.FormEvent<HTMLFormElement>) => void
Output: FormEvent
React.ChangeEvent
Description: Event perubahan input.
Example:
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
Output: ChangeEvent
React.MouseEvent
Description: Event mouse.
Example:
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void
Output: MouseEvent
React.KeyboardEvent
Description: Event keyboard.
Example:
onKeyDown: (e: React.KeyboardEvent) => void
Output: KeyboardEvent
React.Ref
Description: Ref object atau callback.
Example:
const ref = React.useRef<HTMLDivElement>(null)
Output: Ref object
React.PropsWithChildren
Description: Props + children otomatis.
Example:
type Props = React.PropsWithChildren<{ title: string }>
Output: { title: string; children?: ReactNode }
React.ReactPortal
Description: Tipe untuk portal.
Example:
ReactDOM.createPortal(child, container)
Output: Portal

NEXTJS-TYPES

NextPage
Description: Tipe untuk halaman Next.js (App Router).
Example:
import { NextPage } from 'next'
Output: NextPage
PageProps (params, searchParams)
Description: Props halaman App Router.
Example:
type Props = { params: { id: string }; searchParams: { q: string } }
Output: Tipe halaman
LayoutProps
Description: Props layout (children + params).
Example:
type Props = { children: React.ReactNode; params: { slug: string } }
Output: Layout
Metadata
Description: Tipe untuk metadata.
Example:
import { Metadata } from 'next'
Output: Metadata
NextApiRequest / NextApiResponse
Description: Tipe untuk API Routes (Pages Router).
Example:
import { NextApiRequest, NextApiResponse } from 'next'
Output: API types
RouteHandler (App Router)
Description: Tipe untuk route handler.
Example:
import { NextResponse, NextRequest } from 'next/server'
Output: NextRequest, NextResponse
NextAuth types (next-auth)
Description: Tipe untuk NextAuth (auth(), session).
Example:
import { getServerSession } from 'next-auth'
Output: Session

ERROR-HANDLING

try/catch types
Description: Error adalah unknown di catch (useUnknownInCatchVariables).
Example:
catch (e) { if (e instanceof Error) { console.log(e.message) } }
Output: Error safe
asserts condition
Description: Fungsi assertion.
Example:
function assert(condition: any, msg: string): asserts condition { if (!condition) throw Error(msg) }
Output: Narrowing
never type
Description: Untuk fungsi yang tidak kembali.
Example:
function fail(msg: string): never { throw new Error(msg) }
Output: Never
Promise rejection types
Description: Tipe penanganan Promise reject.
Example:
Promise.reject(new Error('fail')) as Promise<never>
Output: Promise<never>

ASYNC-AWAIT

Promise<T>
Description: Tipe return async function.
Example:
async function fetchUser(): Promise<User> {}
Output: Promise
Awaited<T>
Description: Unwrap tipe Promise.
Example:
type Result = Awaited<Promise<Promise<number>>>
Output: number
async function type
Description: Fungsi async otomatis bungkus return dalam Promise.
Example:
const fn = async (): Promise<string> => 'hello'
Output: Promise<string>