Type के Annotations
In this page:
let variable: type = value;
function name(param: type): returnType {
// body
}
String Annotations
string type annotation उपयोग करें, name: string के रूप में लिखा गया, जब एक variable को text data रखना चाहिए। इस तरह annotated होने के बाद, string के अलावा कुछ भी उस variable को assign करना एक compile-time error बन जाता है।
उदाहरण: String Annotations
let name: string = "Neel";
// name = 42; // rejected: number is not a string
console.log(name);
Number और Boolean Annotations
number और boolean types क्रमशः numeric values और true-or-false values describe करते हैं, वही simple name: type annotation syntax उपयोग करते हुए।
TypeScript integers और decimals दोनों के लिए एक single number type उपयोग करती है, अलग int और float types वाली languages के विपरीत।
उदाहरण: Number and Boolean Annotations
let age: number = 30;
let isMember: boolean = true;
console.log(age, isMember);
Array Annotations
Array annotations, type[] के रूप में लिखी गई, specify करती हैं कि उस array में store हर single element किस type से match करना चाहिए, जैसे text values के array के लिए string[]।
यह compiler को एक mismatched item पकड़ने देता है जैसे ही यह add हो, सिर्फ बाद में इसके उपयोग होने पर नहीं।
उदाहरण: Array Annotations
let tags: string[] = ["ts", "types"];
// tags.push(42); // rejected: number is not a string
console.log(tags);
Object Annotations
Object type annotations उन properties describe करती हैं जो एक object के पास होनी चाहिए और हर property की value किस type से match करनी चाहिए, either inline या एक named interface के through।
यह एक object की expected shape को directly code में document करता है, इसे implicit छोड़ने के बजाय।
उदाहरण: Object Annotations
interface Book {
title: string;
pages: number;
}
let book: Book = { title: "TypeScript Basics", pages: 200 };
console.log(book);
Type Annotations क्यों मायने रखते हैं
इन सभी में Type annotations data के एक टुकड़े के intended type को declaration के point पर explicit बनाते हैं, इसे reader को infer करना पड़े इसके बजाय।
यह TypeScript को एक invalid value assign होने का पता development के दौरान ही लगाने देता है, बाद में एक bug के रूप में सामने आने के बजाय।
उदाहरण: Why Type Annotations Matter
let quantity: number = 5;
// quantity = "five"; // caught immediately, not discovered later at runtime
console.log(quantity);
- एक variable को
stringannotate करना और बाद में एक number assign करना, जैसेname = 42। number[]के बजायlet nums: number = [1, 2, 3]लिखना।- हर जगह annotations जोड़ना, जैसे
let age: number = 25, जब inference को type पहले से पता होता।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: