Andrew's Digital Garden

Ambient in Typescript

In [[ts]], 'ambient' is any declaration that doesn't have an implementation. That is, it's a declaration only. They have no run-time impact. Typically, these are defined in d.ts files [[20221216123530-ts-declaration-files]]

There are different types of ambient things, e.g:

  • ambient variable declaration: declare var $: any
  • ambient class declaration: declare class C { foo(); }
  • ambient module: a .d.ts file with a top level import export
  • ambient module declaration: declare module "foo" { .. }

All type-only declarations like interface or type are inherently ambient.

Anything that does not have an implementation, e.g.:

    ambient variable declaration => declare var $: any
    ambient class declaration => declare class C { foo(); } , etc..

A module can be ambient as well; so

    "ambient module" is a .d.ts file with a top level import or export.
    "ambient module declaration" is something of the form declare module "foo" { .. }

In general I've found it best to avoid ambient modules where possible in favour of explicit types that are imported/exported. [[20220801022400-explicit-dependencies-principle]]

https://github.com/microsoft/TypeScript-Handbook/issues/180 https://elfi-y.medium.com/typescript-ambient-module-8816c9e5d426

Ambient in Typescript