ఒక టైప్ ఆసర్షన్ compiler కు "నన్ను విశ్వాసించు, ఈ విలువ X రకం" అని as ఉపయోగించి చెప్పుతుంది. ఇది 런్టైమ్ మార్పిడి లేదా చెక్లు చేయదు — ఇది compiler విలువను ఎలా ఖాళీ చేస్తుందో మార్చుకుంటుంది.
el = .() ;
el. = ;
data = .(str) ;
ఒక టైప్ ఆసర్షన్ compiler కు "నన్ను విశ్వాసించు, ఈ విలువ X రకం" అని as ఉపయోగించి చెప్పుతుంది. ఇది 런్టైమ్ మార్పిడి లేదా చెక్లు చేయదు — ఇది compiler విలువను ఎలా ఖాళీ చేస్తుందో మార్చుకుంటుంది.
el = .() ;
el. = ;
data = .(str) ;
ఒక assertion compiler యొక్క తీర్పును నిరసించుకుంటుంది — మీరు తప్పు చేస్తే, హెచ్చరిక లేకుండా రన్టైమ్ క్రాష్ వస్తుంది:
const x = "hello" as unknown as number; // double assertion — compiler stops complaining
x.toFixed(2); // 💥 runtime error: x.toFixed is not a function
Assertion విలువను ఆ రకం చేయదు; ఇది కేవలం చెక్కర్ను నిశ్శబ్దం చేస్తుంది. మీరు 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 వేరుconst point = { x: 1 } as const; // not a risky cast — narrows to literal/readonly
Assertions కొన్నిసార్లు అవసరం (DOM API లు, ఇప్పటికే చెక్చేసిన unknown సంకుచితం), కానీ ప్రతిది compiler మిమ్మల్ని రక్షించలేని స్థానం.
బిశ్వస్త డేటా కోసం టైప్ గార్డ్లు లేదా స్కీమా ధృవీకరణను ఇష్టపడండి, మరియు ప్రతిটి as ను చిన్న, ఉద్దేశ్యపూర్వక "నాకు బాగా తెలుసు" గా కూర్చోండి.
జూనియర్ నుండి సీనియర్ వరకు వివరణాత్మక సమాధానాలతో IT ఇంటర్వ్యూ ప్రశ్నల లైబ్రరీ.
విరాళం