Declaration Files लिखना
In this page:
declare module "module-name" {
export function name(param: type): returnType;
}
एक Function Declare करना
एक function declare करने का मतलब है इसके parameter names, parameter types, और return type को एक signature के रूप में लिखना, कोई function body के बिना, क्योंकि एक .d.ts file सिर्फ shape describe करती है, कभी behavior नहीं।
उदाहरण: Declaring a Function
declare function formatDate(date: Date, pattern: string): string;
// No body -- just the signature.
console.log("Function declared: formatDate(date, pattern) -> string");
Objects Declare करना
Object shapes declare करने का आमतौर पर मतलब है एक interface लिखना जो हर expected property और इसका type list करे, जो फिर उस kind का object रखने वाले किसी भी variable के लिए type annotation के रूप में उपयोग होती है।
उदाहरण: Declaring Objects
interface UserRecord {
id: number;
name: string;
}
declare const currentUser: UserRecord;
console.log("Object shape declared via interface UserRecord");
एक Module API Declare करना
एक module का public API declare करने का मतलब है एक declare module block लिखना जो module द्वारा available किया गया हर export list करे, तो इसमें से import करना दूसरी जगह पूरी तरह typed हो भले ही module खुद untyped JavaScript हो।
उदाहरण: Declaring a Module API
declare module "legacy-math" {
export function add(a: number, b: number): number;
export function subtract(a: number, b: number): number;
}
console.log("Module API declared for untyped JS module legacy-math");
एक Class API Declare करना
एक class का public API declare करना एक interface declare करने जैसा ही है लेकिन यह constructor parameters और किसी भी static members को भी capture करता है, consumers को कहीं और implemented class के instances new up और type-check करने देते हुए।
उदाहरण: Declaring a Class API
declare class Logger {
constructor(prefix: string);
log(message: string): void;
static instance: Logger;
}
console.log("Class API declared: constructor, instance method, static member");
Declarations Accurate रखना
चूंकि एक .d.ts file का real implementation से कोई connection नहीं है, इसे accurate रखने का मतलब है जब भी underlying JavaScript का actual behavior change हो इसे हाथ से update करना — एक out-of-date declaration type checker से silently झूठ बोलती है।
उदाहरण: Keeping Declarations Accurate
// If the real JS function later adds a parameter,
// this declaration must be updated by hand to match:
declare function sendEmail(to: string, subject: string): void;
console.log("Out-of-date .d.ts files silently lie to the type checker");
declare function formatDate(...)में एक implementation body जोड़ना, जो ambient context में एक error है।- गलत return type declare करना, तो callers उन types पर trust करते हैं जो real JavaScript से match नहीं करती।
- एक module declaration में
exportभूल जाना, तो members importers को visible नहीं होते।
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: