Langsung ke konten

Pelajaran 5 dari 1012 menit

TypeScript basics

TypeScript is JavaScript with types your editor checks as you type. See what it catches, how to annotate values, and how it fits into a project.

Pelajaran ini hanya tersedia dalam bahasa Inggris. Antarmuka halaman tetap dalam bahasa Anda.

Dalam pelajaran ini

  • Explain what TypeScript adds and what it does not
  • Annotate variables, parameters and return values
  • Use union and literal types

What TypeScript adds#

TypeScript is a superset of JavaScript: every JavaScript program is (almost always) valid TypeScript. It adds type annotations that a checker verifies before the code runs. The types are then erased, and what runs is ordinary JavaScript.

mistake.ts
function formatPrice(amount: number): string {  return `Rp ${amount.toLocaleString("id-ID")}`;}formatPrice("85000");1

TypeScript rejects this before you run anything: a string is not a number. Plain JavaScript would run it and quietly print Rp 85000 without the thousands separator, because calling toLocaleString on a string just returns the string. The bug would slip through.

Catatan

Types are checked at build time only. Data arriving at runtime (from an API or a form) is not checked automatically; the error-handling lesson shows how to validate it.

The basic annotations#

annotations.ts
const city: string = "Medan";const population: number = 2_400_000;const isCapital: boolean = false;const tags: string[] = ["food", "lake"];function area(width: number, height: number): number {  return width * height;}

You will rarely write annotations on variables like these, because TypeScript works them out (the next lesson covers inference). Annotate function parameters and the edges of your program; let the rest be inferred.

Object types#

object-type.ts
type Product = {  name: string;  price: number;  description?: string;};const coffee: Product = { name: "Kopi Gayo", price: 90000 };console.log(coffee.description ?? "No description yet");

The ? marks an optional field. Its type becomes string | undefined, so TypeScript makes you handle the missing case; ?? supplies a fallback.

Unions and literal types#

A union says a value can be one of several types. Literal types narrow a string or number to exact values. Together they describe real-world options precisely.

status.ts
type Status = "draft" | "published" | "archived";1function label(status: Status): string {  switch (status) {2    case "draft":      return "Not public yet";    case "published":      return "Live";    case "archived":      return "No longer listed";  }}console.log(label("published")); // "Live"

Only these three strings are allowed. A typo like "publshed" is an error, and your editor autocompletes the valid values.

TypeScript knows every case is handled, so it does not complain that the function might return nothing. Add a fourth status later and this function errors until you handle it.

Running TypeScript#

Browsers and Node.js run JavaScript. In a project, a build tool (Vite, Next.js, esbuild) strips the types, and tsc --noEmit runs the checker. Recent Node.js versions can also run .ts files directly by stripping types.

JavaScript

  • No build step needed
  • Mistakes show up when the code runs
  • Fine for small scripts

TypeScript

  • A checker runs in your editor and CI
  • Many mistakes show up as you type
  • Pays off as code and teams grow

LatihanModel a shipment

Write a Shipment type with an id (string), weightKg (number), and status that is one of "packed", "in-transit" or "delivered". Create one valid shipment.

Tampilkan solusi
solution.ts
type Shipment = {  id: string;  weightKg: number;  status: "packed" | "in-transit" | "delivered";};const parcel: Shipment = { id: "JNE-001", weightKg: 1.5, status: "packed" };console.log(parcel.status);

Recap#

  • TypeScript checks types before code runs, then disappears.
  • Annotate parameters and boundaries; object types describe shapes; ? marks optional fields.
  • Unions and literal types model choices exactly.