ایک user-defined type guard ایسا function ہے جس کی return type ایک type predicate (x is T) ہوتی ہے۔ جب یہ true واپس کرتا ہے، تو compiler calling code میں argument کو T تک narrow کر دیتا ہے — جس سے آپ custom runtime checks کو سمیٹ سکتے ہیں۔
ایک user-defined type guard ایسا function ہے جس کی return type ایک type predicate (x is T) ہوتی ہے۔ جب یہ true واپس کرتا ہے، تو compiler calling code میں argument کو T تک narrow کر دیتا ہے — جس سے آپ custom runtime checks کو سمیٹ سکتے ہیں۔
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 واپس کرنا 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 غلط ہو، تو آپ کو غیر محفوظ narrowing مل جاتی ہے۔ پیچیدہ shapes کے لیے، ایک schema validator (zod) آپ کے لیے درست guards خود بنا دیتا ہے۔
type guards آپ کو من مانے runtime checks کو دوبارہ قابلِ استعمال narrowing functions میں بدلنے دیتے ہیں — جو API/boundaries پر unknown data کی توثیق کے لیے اور union کے members میں فرق کرنے کے لیے ضروری ہیں جب سادہ typeof/in check بذاتِ خود کافی نہ ہو۔
تفصیلی جوابات کے ساتھ IT انٹرویو سوالات کی ایک لائبریری — جونیئر سے سینئر تک۔
عطیہ دیں