एक user-defined type guard भनेको एक function हो जसको return type एक type predicate (x is T) हुन्छ। जब यो true return गर्छ, compiler ले argument लाई calling code मा T मा narrow गर्छ — यसले तपाईंलाई custom runtime checks encapsulate गर्न दिन्छ।
एक user-defined type guard भनेको एक function हो जसको return type एक type predicate (x is T) हुन्छ। जब यो true return गर्छ, compiler ले argument लाई calling code मा T मा narrow गर्छ — यसले तपाईंलाई custom runtime checks encapsulate गर्न दिन्छ।
interface Cat { meow(): void; }
interface Dog { bark(): void; }
// the magic is the return type `pet is Cat`, not just `boolean`
function isCat(pet: Cat | Dog): pet is Cat {
return "meow" in pet;
}
function speak(pet: Cat | Dog) {
if (isCat(pet)) {
pet.meow(); // ✅ narrowed to Cat
} else {
pet.bark(); // ✅ narrowed to Dog
}
}
बिना pet is Cat predicate को, isCat ले boolean return गर्दा pet लाई narrow गर्दैन — compiler ले अझै पनि if भित्र Cat | Dog देख्छ। predicate नै यसलाई सिकाउने कुरा हो।
interface User { id: number; name: string; }
function isUser(x: unknown): x is User {
return (
typeof x === "object" && x !== null &&
typeof (x as any).id === "number" &&
typeof (x as any).name === "string"
);
}
const data: unknown = await res.json();
if (isUser(data)) data.name; // ✅ safely typed as User
Compiler ले आपको predicate मा विश्वास गर्छ — यदि body को logic गलत छ भने, तपाईंले unsafe narrowing पाउनुहुन्छ। जटिल shapes को लागि, एक schema validator (zod) ले तपाईंको लागि सही guards generate गर्छ।
Type guards ले तपाईंलाई arbitrary runtime checks लाई reusable narrowing functions मा परिणत गर्न दिन्छ — unknown डेटा validate गर्नको लागि API/boundaries मा र union को members छुट्याउनको लागि अपरिहार्य जब सरल typeof/in check यसमा पर्याप्त नहुन्छ।