TypeScript: Menangkap Kesalahan Sebelum Sampai Produksi · 2/8
Type-type dasar
Primitive, array, object, function, plus `any`, `unknown`, `never`, dan kapan masing-masing tepat dipakai.
Baca 28 menit
Setelah pelajaran ini kamu bisa
- Memberi anotasi type pada variable, parameter, dan return
- Memberi type pada array, object, dan function
- Memilih dengan tepat antara `any`, `unknown`, dan `never`
- Tahu kapan sebaiknya membiarkan inference yang bekerja
Sintaksnya adalah tanda titik dua dan sebuah type setelah namanya. Hampir cuma itu.
// The eight JavaScript types, annotated.
let name: string = "Ana";
let nights: number = 3;
let paid: boolean = false;
let big: bigint = 10n;
let tag: symbol = Symbol("id");
let nothing: null = null;
let missing: undefined = undefined;
// Arrays: two spellings, identical meaning. Prefer the first.
let tags: string[] = ["beach", "pool"];
let scores: Array<number> = [1, 2, 3];
// Objects: describe the shape inline...
let owner: { name: string; verified: boolean } = { name: "Ana", verified: true };
// ...or give the shape a name, which is what you will usually do.
interface Venue {
id: number;
name: string;
tags: string[];
owner?: { name: string }; // the ? means this property may be absent
}
// Functions: parameter types, then the return type.
function total(nights: number, price: number): number {
return nights * price;
}
// A function that returns nothing is `void`.
function log(message: string): void {
console.log(message);
}Biarkan inference yang bekerja
TypeScript menyimpulkan sebagian besar type dengan sendirinya. Memberi anotasi pada hal yang sudah ia ketahui itu cuma kebisingan, dan ini kebiasaan pemula yang sebaiknya cepat ditinggalkan.
// Noisy: TypeScript already knows both of these.
const name: string = "Ana";
const nights: number = 3;
// Better: identical safety, less to read.
const name = "Ana"; // inferred as string
const nights = 3; // inferred as number
// Return types are inferred too.
function total(nights: number, price: number) {
return nights * price; // inferred as number
}
// Annotate where it genuinely helps:
// 1. Function PARAMETERS - these can never be inferred.
function greet(name: string) {}
// 2. An empty array, which would otherwise be any[].
const ids: number[] = [];
// 3. A public function's return type, to pin the contract deliberately
// so an accidental change becomes an error here, not at every call site.
function findVenue(id: number): Venue | undefined {
return venues.find((v) => v.id === id);
}any, unknown, never
| Type | Artinya | Dipakai saat |
|---|---|---|
any | Berhenti memeriksa ini sepenuhnya | Hampir tidak pernah |
unknown | Bisa apa saja — periksa sebelum dipakai | Data dari luar: JSON, form, API |
never | Ini tidak mungkin terjadi | Pemeriksaan keterlengkapan, function yang selalu throw |
// any switches the checker off. Every mistake below compiles happily.
function withAny(input: any) {
input.whatever.deeply.nested; // no error
input(); // no error
input * 2; // no error
}
// unknown is the honest version: you must prove what it is first.
function withUnknown(input: unknown) {
input.length;
// Error: 'input' is of type 'unknown'.
if (typeof input === "string") {
input.length; // fine - narrowed to string by the check above
}
}
// never: nothing can be assigned to it, which makes it a compile-time alarm.
function assertNever(value: never): never {
throw new Error("Unexpected value: " + String(value));
}Kenapa `unknown` adalah type yang tepat untuk data dari luar: saat runtime, tidak ada yang mencegah server mengirim bentuk yang salah.
Hasil
Tekan Jalankan untuk melihat hasilnya.
Ini jalan di browser kamu, di dalam sandbox. Apa pun yang kamu tulis di sini tidak bisa merusak situs.
Tugas praktik
Buat scratch.ts di proyek ini. Tulis function initials(fullName: string): string yang mengembalikan huruf pertama setiap kata, dalam huruf besar. Lalu coba panggil dengan initials(42) dan dengan initials(). Jalankan bunx tsc --noEmit dan baca kedua error-nya. Lalu jalankan sungguhan dengan node scratch.ts — Node 24 membuang type-nya dan mengeksekusinya.
Hasil yang diharapkan
Dua error compile, lalu output yang jalan dari node.