0
0
Typescriptprogramming~5 mins

Ambient declarations in Typescript

Choose your learning style9 modes available
Introduction

Ambient declarations tell TypeScript about code or variables that exist somewhere else, like in another file or a library. This helps TypeScript understand your code without having the actual code present.

When you use a JavaScript library that does not have TypeScript types included.
When you want to tell TypeScript about global variables or functions defined outside your code.
When you want to describe the shape of code that will be provided later, like from a script loaded in HTML.
When you want to avoid TypeScript errors about missing types for external code.
Syntax
Typescript
declare var variableName: type;
declare function functionName(params): returnType;
declare class ClassName { ... }
declare module 'module-name' { ... }

Use declare to tell TypeScript about something without creating it in the output JavaScript.

Ambient declarations do not generate code; they only provide type information.

Examples
This tells TypeScript there is a global variable called myGlobalVar of type string.
Typescript
declare var myGlobalVar: string;
This tells TypeScript there is a function greet that takes a string and returns nothing.
Typescript
declare function greet(name: string): void;
This describes a class Person with a property and methods, without defining it.
Typescript
declare class Person {
  name: string;
  constructor(name: string);
  greet(): void;
}
This tells TypeScript about a module named my-library and what it exports.
Typescript
declare module 'my-library' {
  export function doSomething(): void;
}
Sample Program

This program declares an ambient global variable externalValue. We assign it a value outside TypeScript's knowledge and then print it. TypeScript won't complain about externalValue because of the declaration.

Typescript
declare var externalValue: number;

globalThis.externalValue = 42;

console.log("The external value is", externalValue);
OutputSuccess
Important Notes

Ambient declarations are only for telling TypeScript about existing code; they do not create variables or functions themselves.

Use ambient declarations carefully to avoid mismatches between declared types and actual runtime behavior.

Ambient declarations often appear in .d.ts files, which only contain type information.

Summary

Ambient declarations use declare to describe code that exists elsewhere.

They help TypeScript understand external or global code without generating JavaScript.

Commonly used for global variables, functions, classes, and modules from other sources.