checkJs का Option
In this page:
{
"compilerOptions": {
"allowJs": true,
"checkJs": true
}
}
Core Concept
checkJs compiler option TypeScript की type checking को plain .js files तक extend करता है (सिर्फ .ts तक नहीं), explicit type annotations के बजाय JSDoc comments और usage patterns से types infer करते हुए।
उदाहरण: Core Concept
/**
* @param {number} x
* @returns {number}
*/
function double(x) {
return x * 2;
}
console.log(double(5));
Basic Setup
इसे tsconfig.json में "allowJs": true के साथ "checkJs": true से enable करें, या एक single file पर top पर // @ts-check comment से बिना global config को छुए।
उदाहरण: Basic Setup
// @ts-check
/**
* @param {string} name
*/
function greet(name) {
console.log("Hello, " + name);
}
greet("Ravi");
Typed Example
एक typed example: /** @param {number} x */ function double(x) { return x * 2; } वाली एक .js file को call sites पर पूरी parameter-type checking मिलती है, भले ही file का extension .ts न हो।
उदाहरण: Typed Example
// @ts-check
/**
* @param {number} x
* @returns {number}
*/
function double(x) {
return x * 2;
}
console.log(double(5)); // call sites get full parameter-type checking
Project Usage
एक असली project में, checkJs legacy .js files में bugs catch करने के लिए useful है जो अभी एक पूरे rewrite के लायक नहीं, lightweight JSDoc annotations उपयोग करते हुए एक पूरी TypeScript conversion के commit करने के बजाय।
उदाहरण: Project Usage
// @ts-check
/**
* @typedef {{ name: string, age: number }} User
*/
/** @param {User} user */
function describe(user) {
return `${user.name} is ${user.age}`;
}
console.log(describe({ name: "Ravi", age: 25 }));
Best Practices
Specific noisy legacy files को individually opt out करने के लिए उनके top पर // @ts-nocheck उपयोग करें, सिर्फ इसलिए project-wide checkJs disable करने के बजाय कि handful of files बहुत ज़्यादा initial errors generate करती हैं।
उदाहरण: Best Practices
// @ts-nocheck
// Opt a specific noisy legacy file out of checking, instead of disabling
// checkJs project-wide.
console.log("Use @ts-nocheck per-file rather than a global opt-out");
checkJsकोallowJsके बिना enable करना, इसलिए JavaScript files include नहीं होती।- एक बड़े codebase पर
checkJsसे errors से flooded होना,// @ts-checkper file उपयोग करने के बजाय। - यह उम्मीद करना कि
@param {number} xcomments runtime पर enforced होंगे।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: