JSDoc की Type Annotations
In this page:
/** @type {TypeName} */
let variable;
/**
* @param {type} param
* @returns {returnType}
*/
function name(param) {}
Core Concept
JSDoc type annotations एक plain JavaScript file को .ts syntax कभी अपनाए बिना TypeScript की type checking और editor autocomplete पाने देते हैं, /** @type {string} */ जैसे comments उपयोग करते हुए जो TypeScript का checker सीधे पढ़ता है।
उदाहरण: Core Concept
/** @type {string} */
let name = "Ravi";
console.log(name);
Basic Setup
एक basic setup को tsconfig.json में "checkJs": true (या एक per-file // @ts-check comment) चाहिए, जिसके बाद comments में @param, @returns, और @type tags असली type information के रूप में parse होते हैं।
उदाहरण: Basic Setup
// @ts-check
/** @param {number} a @param {number} b @returns {number} */
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
Typed Example
एक typed example: /** @param {{name: string, age: number}} user */ function greet(user) { return 'Hi ' + user.name; } greet को पूरी parameter-shape checking देता है, एक misspelled name property वाले call को catch करते हुए।
उदाहरण: Typed Example
/**
* @param {{name: string, age: number}} user
*/
function greet(user) {
return "Hi " + user.name;
}
console.log(greet({ name: "Ravi", age: 25 }));
Project Usage
एक असली project में, JSDoc annotations उन JavaScript libraries के लिए standard middle step हैं जो बिना build step जोड़े या source को .ts में rewrite किए TypeScript consumers को type information ship करना चाहती हैं।
उदाहरण: Project Usage
/**
* @typedef {{ id: number, name: string }} User
*/
/** @param {User} user */
function display(user) {
return `${user.id}: ${user.name}`;
}
console.log(display({ id: 1, name: "Ravi" }));
Best Practices
@typedef उपयोग करें एक complex JSDoc shape को name और reuse करने के लिए कई functions में, जहां भी इसकी ज़रूरत हो वहां वही inline object-type comment repeat करने के बजाय।
उदाहरण: Best Practices
/**
* @typedef {{ id: number, name: string }} User
*/
/** @param {User} u */
function idOf(u) { return u.id; }
/** @param {User} u */
function nameOf(u) { return u.name; }
console.log(idOf({ id: 1, name: "Ravi" }));
- Type को गलत जगह लिखना, जैसे
@param x {number}बजाय@param {number} xके। - एक regular comment
/* ... */उपयोग करना/** ... */के बजाय, इसलिए JSDoc ignore हो जाता है। checkJsया// @ts-checkभूल जाना, इसलिए annotations कुछ नहीं करते।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: