Hossam El-Deen
Hossam El-Deen

Reputation: 1112

type-declaration file for non-module in angular typescript

I'm building a website for Beaker Browser using Angular6.

Beaker Browser has a built-in class called DatArchive. I want to create a type-declaration file for it.

When this class was used in only one file, I simply wrote

declare class DatArchive {
  static selectArchive(opts: any): Promise<DatArchive>;
  static create(opts: any): Promise<DatArchive>;
  constructor(datUrl: String);
  url: string;
}

in the file and everything worked like a charm. However, when I wanted to extract it into its own file, I tried:

export declare class DatArchive {
  static selectArchive(opts: any): Promise<DatArchive>;
  static create(opts: any): Promise<DatArchive>;
  constructor(datUrl: String);
  url: string;
}
...
// in other files
import { DatArchive } from 'dat-archive';

And although it passed compilation, in runtime, seemingly, it was looking for a DatArchive inside a module, but a DatArchive is a top-level (on window object) class.

So, the question:

In Angular/Typescript, how to write a type-declaration file for a class that is NOT part of a module?

Upvotes: 0

Views: 2211

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18292

You can just write this in a declaration file (call it beaker-browser.d.ts):

declare class DatArchive {
  static selectArchive(opts: any): Promise<DatArchive>;
  static create(opts: any): Promise<DatArchive>;
  constructor(datUrl: String);
  url: string;
}

Putting this into a declaration file makes it a global declaration, so just can you just use let dataArchive = new DataArchive(url); without importing anything.

This is because you don't need to import anything, as the code itself is already in the environment. Creating a declaration file you just tell the compiler that such a class exists, without providing a definition (similar to what you were doing initially, but available to the whole project).

Upvotes: 2

Related Questions