A type assertion ngandhani compiler "pitakon marang aku, nilai iki tegese X" nganggo as. Iku njaluk ora ana runtime conversion utawa checking — mung bab carane compiler ngrewangi nilai.
el = .() ;
el. = ;
data = .(str) ;
A type assertion ngandhani compiler "pitakon marang aku, nilai iki tegese X" nganggo as. Iku njaluk ora ana runtime conversion utawa checking — mung bab carane compiler ngrewangi nilai.
el = .() ;
el. = ;
data = .(str) ;
Pustaka pitakon wawancara IT kanthi jawaban rinci — saka Junior nganti Senior.
NyumbangSesarengan overrides compiler nyang — yen salah, sampeyan entuk runtime crash tanpa rembugan:
const x = "hello" as unknown as number; // double assertion — compiler stops complaining
x.toFixed(2); // 💥 runtime error: x.toFixed is not a function
Asserting ora nggawe nilai iku jenis kasebut; mung suda checker. Sampeyan wis njupuk tanggung jawab kanggo benar saka compiler.
// 1. type guard — actually verify at runtime
if (typeof input === "string") { /* input is string, proven */ }
// 2. validation library (zod) for external data
const user = UserSchema.parse(data); // throws if shape is wrong
as const bedaconst point = { x: 1 } as const; // not a risky cast — narrows to literal/readonly
Assertions kadhang butuh (DOM APIs, narrowing unknown sing wis dicek), nanging saben siji iku papan compiler ora bisa nglindhungi sampeyan.
Nerangno type guards utawa schema validation kanggo data sing ora dipercaya, lan gawe saben as minangka cilik, disengaja "aku ngerti luwih" sing kudu sampeyan yakin ngenani.