Ambient module
- TypeScript course
- Intermediate
- Lesson 59/89
- 4 min
Learn to declare ambient modules.
What is an ambient module?
An ambient module tells TypeScript about a JS module that exists but has no type information. It is declared with declare module and the module name is quoted. Functions and variables exported inside gain types.
declare module "old-module" {
export function greet(name: string): string;
}Wildcard module
With the wildcard declare module "*" you can describe all modules matching a pattern. For example, it is used to give type information when importing CSS or image files. The default export is specified with export default.
declare module "*.css" {
const content: string;
export default content;
}Practice Declare the "selam" ambient module
Declare an ambient module "selam". Export a function merhaba(name: string): string inside it. Then print "modül hazır" with console.log.
Starter code
// "selam" ambient modülünü bildir
// içinde merhaba(name: string): string dışa aktar
console.log("modül hazır");Sample solution
declare module "selam" {
export function merhaba(name: string): string;
}
console.log("modül hazır");Expected output
modül hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the purpose of declare module "x" { ... }?
- Creates a new JavaScript module
- Loads the module at runtime
- Compiles the module's JavaScript code
- Tells TypeScript about an existing JS module Correct answer
Explanation: declare module provides type information for an existing JS module; it does not create a new module or generate JavaScript code.
2 Ambient module keyword
declare ____ "eski" { export function x(): void; }
declare module "eski" { export function x(): void; }
Explanation: To declare an ambient module use `declare module`; the module name is quoted.
3 Ambient module parts
| Term | Meaning |
|---|---|
declare module |
Ambient module start |
export function |
Function inside module |
"*" |
Wildcard |
export default |
Default export |