In TypeScript, ambient declarations are used to tell the compiler about the shape of external code that is not written in TypeScript. They allow you to use existing JavaScript libraries or code in your TypeScript projects without causing type errors. Ambient declarations are typically defined in .d.ts
files, which stand for declaration files.
Here's a step-by-step guide on how to create and use ambient declarations in TypeScript:
Create a new file with a .d.ts
extension, for example, myLibrary.d.ts
. This file will contain the ambient declarations for the external code.
typescript// myLibrary.d.ts
declare module 'my-library' {
// Declare the types for the external module or library here
// Example: If the library exports a function
export function myFunction(param: string): void;
// Example: If the library has a class
export class MyClass {
constructor(name: string);
sayHello(): void;
}
// Add more declarations as needed
}
In this example, we're declaring a module named 'my-library'
and specifying the types for a function (myFunction
) and a class (MyClass
).
In your TypeScript code, reference the declaration file using a triple-slash directive at the top of your file.
typescript// myApp.ts
/// <reference path="./myLibrary.d.ts" />
// Now you can use the external module in your TypeScript code
import { myFunction, MyClass } from 'my-library';
// Use the declared types
myFunction('Hello, world!');
const instance = new MyClass('John');
instance.sayHello();
If the external library is not already installed, install it using your package manager. For example, if using npm:
bashnpm install my-library
Compile your TypeScript code using the TypeScript compiler (tsc).
bashtsc myApp.ts
Now you can run the generated JavaScript code (along with the ambient declarations) in your project.
bashnode myApp.js
This way, TypeScript understands the shape of the external library based on the ambient declarations, allowing for type-checking and autocompletion in your editor, while still using the existing JavaScript code.
Note: Depending on the library, you may find existing declaration files on DefinitelyTyped (https://definitelytyped.org/) or in the library's repository. If available, it's often preferable to use those declaration files rather than creating your own.