Type Assertions — TypeScript

Type assertion memberitahu TypeScript bahwa kamu tahu tipe lebih spesifik: as keyword: const input = document.getElementById("email") as HTMLInputElement; input

Type assertion memberitahu TypeScript bahwa kamu tahu tipe lebih spesifik:

as keyword:

const input = document.getElementById("email") as HTMLInputElement;
input.value = "[email protected]";

satisfies (TS 4.9+) — validasi tipe tanpa mengubah tipe:

type Config = Record<string, string | number>;
const config = {
  port: 3000,
  host: "localhost"
} satisfies Config;
// config.port tetap number (bukan string | number)

Non-null assertion !:

function process(value?: string) {
  console.log(value!.toUpperCase()); // "saya yakin ini bukan null"
}

Perhatian: Type assertion tidak mengubah runtime behavior. Gunakan hanya jika kamu benar-benar yakin tentang tipe-nya.

Yang akan kamu pelajari