आपका पहला TypeScript Program
In this page:
// hello.ts
const message: string = "text";
console.log(message);
Hello World लिखना
Classic पहला program console.log उपयोग करके एक Hello World message दिखाता है, बिल्कुल plain JavaScript जैसा। TypeScript आपको यह familiar statement बिना बदले लिखने देती है जबकि program बढ़ने पर type information add करने का option देती है।
उदाहरण: Writing Hello World
console.log("Hello, World!");
Variables उपयोग करना
Variables एक program को बाद में उपयोग के लिए information store करने देते हैं, और TypeScript intended kind of value को explicit बनाने के लिए एक type annotation attach कर सकती है। एक बार variable typed हो जाए, गलत kind की value assign करना code run होने से पहले ही पकड़ लिया जाता है।
उदाहरण: Using Variables
let username: string = "Riya";
// username = 42; // TypeScript rejects assigning the wrong type
console.log(username);
एक Function बनाना
Functions reusable instructions को साथ group करते हैं, और TypeScript आपको हर parameter का type और function जो value return करता है वह specify करने देती है।
इसका मतलब है कि एक argument में typo, जैसे number expected होने पर string pass करना, compiler द्वारा तुरंत flag हो जाता है।
उदाहरण: Creating a Function
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Sam"));
Arrays उपयोग करना
Arrays एक variable में कई values store करते हैं, और TypeScript number[] जैसी syntax उपयोग करके एक array के expected values का type specify कर सकती है। एक typed array में एक mismatched value push करने की कोशिश एक compile-time error produce करती है।
उदाहरण: Using Arrays
let scores: number[] = [10, 20, 30];
// scores.push("high"); // rejected: string is not a number
scores.push(40);
console.log(scores);
Compile और Run करना
एक TypeScript file लिखने के बाद, tsc compiler type annotations strip करके इसे plain JavaScript में transform करता है। Generated .js file फिर Node.js या एक browser जैसे किसी भी standard JavaScript runtime के साथ run किया जा सकता है।
उदाहरण: Compiling and Running
let message: string = "Ready to compile";
console.log(message);
// tsc strips ": string" and produces a plain .js file to run with node
let username: stringdeclared एक variable को बाद मेंusername = 42से assign करना, जिसे compiler reject करता है।function add(a, b)जैसे एक function में parameter types छोड़ देना, जो strict settings के तहत उन्हें implicitlyanyबना देता है।- एक
number[]array में गलत type की value push करना, जैसेnums.push("5"), जो एक compile error है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: