bcherny bcherny - 2 months ago 11x
TypeScript Question

How do I declare an ambient namespace for an NPM module?

Module is here: https://github.com/coatue/SlickGrid

It ambiently exports the following structure:

namespace Slick {
class Grid {...}
namespace Data {
class DataView {...}

So I created a file typings.d.ts in the root of the repo, containing:

declare namespace Slick {
export class Grid {...}
namespace Data {
export class DataView {...}

And in the repo's package.json, I put
"typings": "./typings.d.ts"

However, this doesn't seem to work.

I want
to be available in every file in the consuming project, without having to explicitly
import Slick from "slickgrid2"
. What's the right syntax to use here? Typescript handbook/docs don't cover this case.


It looks like TypeScript won't try to load the typing that way unless you import the module. See Typings for NPM Packages. That source also says that you should use "external modules" instead of namespaces (or "internal modules"), which is what you're doing here.

What you ask for, to have your type definitions "be available in every file in the consuming project" without having to do an import, isn't possible, as far as I know. At the least, you'd need to add a triple-slash reference directive, e.g. /// <reference path="path/to/typings.d.ts"/>. I think you have a couple of workaround options:

First, you could tell your users to reference your typing directly whenever they need it: /// <reference path="path/to/node_modules/slickgrid2/typings.d.ts" />

Second, you could leverage DefinitelyTyped and typings:

  1. Publish your typings to DefinitelyTyped.
  2. Users can then, in their projects, use typings install --source dt --global to install your typing.

You'll get a typings folder as a peer of node_modules. This will contain index.d.ts. The tool will automatically add the reference to your typings file. Now, your users can just put /// <reference path="typings/index.d.ts" /> at the top of every file where they want your type definitions. They may have been including that file anyway for other types.