Describe external variables
A browser global, injected configuration object, or host-provided constant is available at runtime but absent from the current TypeScript source.
TypeScript · Const
The declare keyword describes a runtime-provided symbol to TypeScript without implementing it in the current source. It is commonly used in .d.ts files and for external variables, functions, classes, namespaces, and modules.
The declare modifier tells TypeScript that a value, function, class, namespace, or module exists without providing its implementation. It is used to describe runtime-provided APIs, commonly in declaration files, and contributes type information rather than JavaScript behavior.
declare const name: Type;
declare let name: Type;
declare var name: Type;
declare function name(...parameters): ReturnType;
declare class Name { ... }
declare namespace Name { ... }
declare module "module-name";declare const config: { apiUrl: string };
export function request(path: string) {
return fetch(`${config.apiUrl}${path}`);
}The declaration supplies a compile-time type for a value provided by another script or runtime environment; it emits no initialization for config.
A browser global, injected configuration object, or host-provided constant is available at runtime but absent from the current TypeScript source.
A JavaScript library has no bundled TypeScript types and its callable API must be exposed to a TypeScript consumer.
An existing JavaScript constructor and its instance members need to be represented for consumers without rewriting the implementation.
A package or module lacks type declarations and needs an ambient module declaration so imports can be checked.
declare tells the compiler that a symbol exists elsewhere, so TypeScript can type-check uses without an implementation in the current source. It is useful for describing APIs supplied by JavaScript libraries or the runtime.
Follow-up: What happens at runtime? Nothing is created by declare; the external code must define the symbol before use.
Use declare const for a read-only externally supplied variable, declare let for a block-scoped variable, and declare var for a variable with var-style semantics. The declaration gives TypeScript the variable's type but not its value.
Follow-up: How would you describe an external function? Use declare function with its parameter and return types, such as declare function greet(message: string): void.
A declaration file describes types or values without implementations and conventionally uses the .d.ts extension. Such files are consumed for type-checking and do not produce JavaScript output.
Follow-up: How can an untyped module be acknowledged quickly? Add an empty declare module "module-name"; declaration, though this provides the module with an any-like fallback.
declare vardeclare letdeclare functiondeclare classdeclare namespacedeclaration files.d.tsdeclare module