Type Narrowing के Best Practices
In this page:
Early Narrow करें
एक function के अंदर invalid या unsupported cases को जितनी जल्दी possible हो check करें — early narrowing nesting घटाता है और function की बाकी logic को एक already-validated, simpler type पर operate करते रखता है।
उदाहरण: Narrow Early
function process(value: string | null) {
if (value === null) return;
console.log(value.toUpperCase());
}
process("hello");
Built-in Guards उपयोग करें
जहां भी apply हो custom logic के बजाय typeof, instanceof, Array.isArray, और in operator जैसे standard runtime checks को prefer करें — TypeScript इन सभी को natively समझता है और वे दूसरे readers को intent clearly communicate करते हैं।
उदाहरण: Use Built-in Guards
function describe(value: string | number | string[]) {
if (Array.isArray(value)) return "array";
if (typeof value === "string") return "string";
return "number";
}
console.log(describe([1, 2]));
Discriminants उपयोग करें
related object variants की एक family के लिए, kind या status जैसी एक shared literal discriminant property add करें — उस एक property को check करना TypeScript को एक union में correct variant select करने का एक पूरी तरह reliable तरीका देता है।
उदाहरण: Use Discriminants
type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };
function area(shape: Shape) {
return shape.kind === "circle" ? Math.PI * shape.radius ** 2 : shape.side ** 2;
}
console.log(area({ kind: "square", side: 4 }));
Custom Type Guards लिखें
जब built-in guards genuinely काफी न हों, एक custom function लिखें जो value is User जैसा एक type predicate return करे — इन checks को scrupulously accurate रखें, क्योंकि TypeScript predicate जो भी claim करता है उसे आगे verify किए बिना trust करता है।
उदाहरण: Write Custom Type Guards
interface User { name: string; }
function isUser(value: unknown): value is User {
return typeof (value as User)?.name === "string";
}
const data: unknown = { name: "Ravi" };
if (isUser(data)) console.log(data.name);
Unnecessary Assertions Avoid करें
सिर्फ एक error silence करने के लिए एक type assertion की ओर पहुंचने से बचें — एक assertion compiler को बिना किसी runtime check के आप पर trust करने के लिए कहता है, इसलिए जब भी value users, APIs, storage, या किसी और untrusted source से आए तो एक असली guard prefer करें।
उदाहरण: Avoid Unnecessary Assertions
function getLength(value: unknown): number {
if (typeof value === "string") return value.length;
return 0;
}
console.log(getLength("hello"));
- Early return करने के बजाय बड़े
if/elseblocks nest करना, जो narrowed code को पढ़ना मुश्किल बनाता है। - किसी ऐसी चीज़ के लिए एक custom type guard लिखना जो
typeofयाinstanceofपहले से check कर सकता था। - Narrowing के लिए
typeof x === "object"उपयोग करना और यह भूल जाना किnullभी"object"है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: