2

Most .d.ts files are straightforward to use, jQuery.d.ts for instance. But now I have hit up against chrome-app.d.ts and it isn't clear (to me!) how this typings file can be imported. chrome-app.d.ts comprises a series of module definitions, each containing interfaces and exported functions. Here is a snip:

declare module chrome.app.runtime {
    interface LaunchData {
        id?: string;
        ......
        ......
}

declare module chrome.app.window {
    interface ContentBounds {
        left?: number;
        ......
        ......
    export function current(): AppWindow;
    export function get(id: string): AppWindow;
    export function getAll(): AppWindow[];
}

and so on, seven modules in total. The module names are not quoted. There is no top level export declaration.

How can I use (i.e. import) this definition file in my ts? I would like to use chrome.app.window.get() and so on, staying with the JS definitions in the Goog documentation. SO answer Using a Typescript .d.ts file that doesn't declare a module nearly works for my problem. In that solution, add to a supplementary .d.ts file with a quoted module name:

declare module 'chrome.app.runtime' { export = chrome.app.runtime; }

and indeed I can use this:

import chromeAppRuntime = require('chrome.app.runtime');

but I cannot use this:

import chrome.app.runtime = require('chrome.app.runtime');

So would this be OK and preserve the tool chain:

import fooBar = require('chrome.app.runtime');
var chrome = {app: {runtime: fooBar}};

Is there anything simpler :)

Community
  • 1
  • 1
timecc
  • 161
  • 1
  • 11
  • See this question, I think it has the best answer: https://stackoverflow.com/questions/43655106/how-to-use-chrome-app-d-ts-type-in-angular-cli-1-0-1-app – Andrew Shepherd Feb 13 '18 at 11:03

1 Answers1

2

The chrome object is a global namespace object, not some external module. This chrome-app.d.ts file describes the global object that exists within the scope of a Chrome extension. It uses the (discouraged/deprecated) module keyword, which is identical to the less confusing namespace keyword in newer versions of TypeScript. In other words, this d.ts file is declaring namespace objects in the global scope.

To use this d.ts file, you don’t import it, you pass it directly to the compiler along with your own code:

tsc my/extension.ts chrome-app.d.ts

Your code then uses the chrome object directly just like you would use window or document directly from the global scope of a script that runs in the DOM. (The TypeScript compiler implicitly includes the bundled lib.d.ts when you run it, which exposes the DOM API.)

C Snover
  • 17,908
  • 5
  • 29
  • 39