Ambient Declarations की जानकारी
In this page:
declare const name: type;
declare function name(param: type): returnType;
declare module "module-name";
declare उपयोग करना
declare keyword एक मौजूदा value, function, class, या दूसरी declaration describe करता है जो TypeScript को मानना चाहिए runtime पर exist करती है, बिना TypeScript खुद इसके लिए कोई code generate किए।
उदाहरण: Using declare
declare const VERSION: string;
// Assume VERSION is injected by the build tool at runtime.
console.log("Would use VERSION here in a real ambient setup");
Ambient Interfaces
Ambient interfaces मौजूदा objects का shape describe कर सकते हैं, जैसे एक browser API या एक third-party script से मिले objects, किसी runtime implementation provide करने की ज़रूरत के बिना।
उदाहरण: Ambient Interfaces
declare interface Window {
myGlobalFlag: boolean;
}
// Describes a value assumed to exist on window at runtime.
console.log("Ambient interface declared for Window.myGlobalFlag");
Ambient Functions
Ambient function declarations उन functions को describe करते हैं जो current TypeScript file के बाहर implemented हैं — अक्सर plain JavaScript, एक <script> tag, या एक native environment में — तो TypeScript अब भी इनकी calls type-check कर सकता है।
उदाहरण: Ambient Functions
declare function trackEvent(name: string): void;
// trackEvent is assumed to be implemented elsewhere (e.g. a <script> tag).
console.log("Ambient function trackEvent declared");
Ambient Modules
एक ambient module declaration एक JavaScript module द्वारा exported types describe करती है जो अपने own TypeScript types ship नहीं करता, effectively बाहर से एक library के लिए type information लिखते हुए।
उदाहरण: Ambient Modules
declare module "legacy-lib" {
export function doSomething(): string;
}
// Provides types for a JS module with no types of its own.
console.log("Ambient module declared for legacy-lib");
Declaration Files
Ambient declarations आमतौर पर .d.ts declaration files में store होती हैं, जो project के बाकी हिस्से को बिना कोई executable code रखे type information प्रदान करती हैं।
उदाहरण: Declaration Files
// types.d.ts (declaration file, no runtime code)
// declare function legacyAdd(a: number, b: number): number;
console.log("Declaration files contain only type information, no executable code");
declare const x: stringउपयोग करना और इसके variable create करने की उम्मीद करना, जब यह सिर्फ compiler को बताता है कि यह पहले से exist करता है और एक missing value एक runtimeReferenceErrorदेती है।- एक ambient declaration में एक initializer डालना, जैसे
declare const VERSION = 1 + 1;, जो allowed नहीं है। declare functionके अंदर function bodies लिखना, जब ambient declarations में सिर्फ signatures होनी चाहिए।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: