any से बचना
In this page:
let value: SpecificType; // prefer a specific type over any
function identity<T>(input: T): T { // or a generic
return input;
}
any क्यों Risky है
any के रूप में typed एक value को लगभग किसी भी जगह zero compiler checks के साथ pass किया, call किया, और access किया जा सकता है — यह exactly उन mistakes को silently hide कर सकता है जिन्हें catch करने के लिए TypeScript मौजूद है, program चलने से पहले।
उदाहरण: Why any Is Risky
let value: any = "hello";
value = value.nonExistentMethod(); // compiles, but crashes at runtime
console.log("any bypasses all compiler checks");
Specific Types उपयोग करें
जब एक value की expected shape असल में जानी जाती हो, तो उस shape को सीधे एक type के रूप में लिखें — specific types असली autocomplete देते हैं और उन invalid assignments या missing properties को तुरंत catch करते हैं जो any को unnoticed जाने देता।
उदाहरण: Use Specific Types
interface User {
name: string;
age: number;
}
function greet(user: User) {
return `Hello, ${user.name}`;
}
console.log(greet({ name: "Ravi", age: 25 }));
any के बजाय Generics उपयोग करें
Generics एक function के input और output types के बीच relationship को कई अलग concrete types के across preserve करते हैं, जो usually reusable functions के लिए any से बेहतर fit है जिन्हें generically काम करना हो।
उदाहरण: Use Generics Instead of any
function identity<T>(value: T): T {
return value;
}
console.log(identity(42), identity("hello"));
Untrusted Data के लिए Unknown उपयोग करें
unknown उन values के लिए any से कहीं ज़्यादा safer choice है जिनका type genuinely पहले से नहीं पता, क्योंकि यह program को किसी भी चीज़ के लिए उपयोग होने से पहले value को एक असली check से narrow करने के लिए मजबूर करता है।
उदाहरण: Use Unknown for Untrusted Data
function process(value: unknown) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
process("hello");
Explicit Escape Hatches सावधानी से उपयोग करें
कभी-कभी एक library integration या एक migration को genuinely एक escape hatch के रूप में एक type assertion की ज़रूरत होती है — उन assertions को पूरे codebase में any पहुंचने के बजाय narrow और local रखें।
उदाहरण: Use Explicit Escape Hatches Carefully
interface LegacyApi {
oldMethod(): string;
}
const legacy = {} as LegacyApi; // narrow, local, documented escape hatch
console.log(typeof legacy.oldMethod);
- एक error silence करने के लिए एक value को
anydeclare करना, इसलिएvalue.nonExistentMethod()compile होता है और runtime पर crash करता है। - Parameters को untyped छोड़ना, जो implicitly
anyबन जाते हैं जब तकnoImplicitAnyon न हो। - Arrays के लिए एक typed array या generic के बजाय
any[]उपयोग करना, element type checks खोते हुए।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: