Strict Mode के Options
In this page:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}
strict Enable करना
strict option एक साथ कई stronger type-checking flags का एक पूरा collection enable करता है, यही कारण है कि ज़्यादातर style guides इसे बाद में retrofit करने के बजाय सबसे पहले commit से ही on करने की recommend करते हैं।
उदाहरण: Enabling strict
// tsconfig.json
// { "compilerOptions": { "strict": true } }
console.log("strict enables a whole bundle of stronger checks at once");
strictNullChecks
strictNullChecks null और undefined को हर चीज़ को silently assignable होने के बजाय अलग types बनाता है, code को उपयोग करने से पहले missing value की possibility explicitly handle करने पर मजबूर करते हुए — यह एक अकेला runtime crashes की एक बड़ी class पकड़ लेता है।
उदाहरण: strictNullChecks
function getLength(s: string | null): number {
if (s === null) return 0;
return s.length; // safe: s narrowed to string here
}
console.log(getLength(null));
noImplicitAny
noImplicitAny वहां error report करता है जहां TypeScript एक untyped value के लिए silently any type infer कर देता, type safety के quietly codebase से leak होने के सबसे आम तरीकों में से एक को बंद करते हुए।
उदाहरण: noImplicitAny
function double(x: number): number {
return x * 2;
}
// Without noImplicitAny, an untyped parameter would silently become 'any'.
console.log(double(5));
strictFunctionTypes और strictBindCallApply
Strict function-type और bind/call/apply checks safety improve करते हैं जब functions variables को assign होती हैं या indirectly invoke होती हैं, parameter-type mismatches पकड़ते हुए जिन्हें looser settings पास होने देती।
उदाहरण: strictFunctionTypes and strictBindCallApply
function greet(name: string): void {
console.log("Hello", name);
}
const fn: (name: string) => void = greet;
fn("Ravi");
Individual Strict Options चुनना
ज़्यादातर projects को सिर्फ strict: true on करने से फायदा होता है, लेकिन individual sub-options एक-एक करके enable किए जा सकते हैं जब एक पुराना, loosely-typed codebase migrate किया जा रहा हो जो एक साथ हर strict check absorb नहीं कर सकता।
उदाहरण: Choosing Individual Strict Options
// tsconfig.json
// { "compilerOptions": { "strictNullChecks": true, "noImplicitAny": false } }
console.log("Individual flags can be enabled incrementally during migration");
- एक बड़े project में
strictदेर से on करना और errors से flooded होना, बजाय उन्हें gradually fix करने के। strictNullCheckserrors को silence करने के लिए हर जगह!याas anyउपयोग करना बजायnullजांचने के।noImplicitAnyके under parameters untyped छोड़ना, जो एक error है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: