Search code examples
typescriptcoffeescripttypescript-typingsmodule-augmentation

How to convert custom type definition file to npm type definition file


I have a custom module definition file for a dependency written in CoffeeScript in my typescript project.

It looks like the following and works great:

src/@types/dependency-name.d.ts

declare module 'dependency-name' {
  import EventEmitter from 'eventemitter3';

  /**
  * omitted
  */

  interface ICable {
    new (channels: Record<string, ISubscription>): ICable;

    channels: Record<string, ISubscription>;

    channel: (name: string) => ISubscription | undefined;
    setChannel: (name: string, channel: ISubscription) => ISubscription;
  }
  export const Cable: ICable;
}

So I want to contribute to this project and submit a type definition file.

What I tried is:

  1. Forked the original CoffeeScript project,
  2. Copied the above definition to index.d.ts
  3. Add the following line to pacakge.json:
"typings": "index.d.ts",
  1. Installed forked repository in my typescript project for testing.

However, it does not recognize the added index.d.ts file. Shows type definition is missing error.

I've seen this post and guessed that the issue is this one:

be written as external modules

But I don't understand it. Can someone guide me to convert my custom typing (module augmentation, I guess?) to correct type definition file for package.json?


Solution

  • I would recommend looking directly at the TypeScript handbook page linked from the post you linked, as the post itself is rather old and the copy of the text there is a bit outdated. In particular, "types" is now preferred over "typings" in package.json, although both should still work.

    However, you and the post are correct that the issue is one of ambient external modules ("ambient modules") vs. non-ambient ones ("external modules"). You should just need to remove the declare module block wrapping around your file, leaving its contents at the top level. That will transform your declarations from ambient to non-ambient and should make it work.