Typescript ambient declarations
Created By: chatGPT
TypeScript ambient declarations allow you to define types for variables, functions, and other entities that are defined in an external library or are globally available. This is particularly useful when you're working with libraries written in JavaScript, where TypeScript's type inference is not available.
// Example of an ambient declaration for a variable
declare const myLibrary: {
myFunction(param: string): number;
};
You can also declare a module for a third-party library. This is done using the
declare module
syntax. It allows you to specify the types for its exports efficiently.// Example of declaring a module
declare module 'my-module' {
export function myFunction(param: number): void;
export const myVariable: string;
};
If you have custom types that you want to reuse across your application, ambient declarations are a great way to create a typings file. You can create a
*.d.ts
file where you will place all your declarations.// my-types.d.ts
declare global {
interface MyCustomObject {
id: number;
name: string;
}
}
export {}; // Needed to make this file a module
To use ambient declarations in your TypeScript files, simply import them as needed. The ambient declarations will seamlessly integrate into your existing code enabling type checking and autocompletion.
// my-file.ts
/// <reference path='./my-types.d.ts' />
const obj: MyCustomObject = {
id: 1,
name: 'Test'
};
It's important to note that module resolution settings in your
tsconfig.json
can impact how TypeScript finds and applies these declarations. Be sure to set typeRoots
or types
if you are managing third-party packages.{
"compilerOptions": {
"typeRoots": ["node_modules/@types", "src/types"]
}
}