Type का Inference
In this page:
let variable = value; // type inferred from value
Basic Inference
जब एक variable एक value से initialize होता है, TypeScript उस value से उसका type automatically infer कर सकता है बिना किसी explicit annotation की ज़रूरत के। let age = 25 लिखना age को inferred type number देता है, कोई extra syntax चाहिए बिना।
उदाहरण: Basic Inference
let age = 25; // inferred as number, no annotation needed
console.log(typeof age, age);
Inference with const
Constants को भी जो भी value वे assign होते हैं उससे एक inferred type मिलता है, और चूंकि const values को कभी reassign नहीं किया जा सकता, TypeScript कभी-कभी एक similarly initialized let से ज़्यादा specific literal type infer कर सकता है।
उदाहरण: Inference with const
const name = "Fixed"; // inferred as the literal type "Fixed", not just string
console.log(name);
Inference in Arrays
TypeScript एक array के element type को सीधे उसके initializer के अंदर रखे values से infer कर सकता है, तो const nums = [1, 2, 3] automatically एक number[] के रूप में समझा जाता है, कोई annotation ज़रूरत नहीं।
Mixed-type array literals उन types के एक union के रूप में infer होते हैं।
उदाहरण: Inference in Arrays
const nums = [1, 2, 3]; // inferred as number[]
console.log(nums);
Inference in Expressions
Types भी expressions और operations के result से infer होते हैं, जैसे एक function का return type उसके return statement से जो भी असल में produce होता है उससे infer होना।
यह आपको simple functions पर return types annotate करने से बचने देता है जबकि TypeScript उन्हें फिर भी पूरी तरह checked रखता है।
उदाहरण: Inference in Expressions
function add(a: number, b: number) {
return a + b; // return type inferred as number
}
console.log(add(2, 3));
Inference and Explicit Types
Type inference unnecessary explicit annotations की ज़रूरत घटाता है, code को कम cluttered रखते हुए, जबकि explicit annotations तब भी उपयोगी हैं जब आप एक intended type clearly document करना चाहें या एक variable को जानबूझकर TypeScript के otherwise infer किए जाने वाले से narrower type तक restrict करना चाहें।
उदाहरण: Inference and Explicit Types
let count = 5; // inferred, no clutter
let id: number = 5; // explicit, documents intent
console.log(count, id);
let x;बिना किसी value के declare करना और एक type infer होने की उम्मीद करना, जब यहanyबन जाता है।- यह उम्मीद करना कि
const name = "Fixed"सिर्फstringहोगा, जब यह literal type"Fixed"के रूप में inferred है। - एक empty array जैसे
const items = []initialize करना और एक specific element type की उम्मीद करना।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: