tugberk
tugberk

Reputation: 58494

Importing custom declaration files with TypeScript

I have the following TypeScript declaration for an npm package named foo which (let just assume for the sake of this example) does not have a declaration file anywhere that I can pull.

declare module "foo" {
    export function getPerpetualEnergy(): any[];
    export function endWorldHunger(n: boolean): void;
}

I have placed that declaration inside ./typings/foo.d.ts file and updated my typeRoots folders to below (inside ./tsconfig.json file):

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "strictNullChecks": true,
        "moduleResolution": "node",
        "typeRoots": [
            "./typings/",
            "./node_modules/@types/"
        ]
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.test.ts"
    ]
}

and I have tried to use it from a .ts like below:

import * as foo from 'foo';
foo.endWorldHunger(true);

However, it was not able to resolve this. It was complaining to me inside VS Code, too (since I had noImplicitAny: true, I suppose, considering this).

I have changed my consuption to below and it worked out:

/// <reference path="../../typings/foo.d.ts"/>
import * as foo from 'foo';
foo.endWorldHunger(true);

Do I really need that reference declaration? I am expecting that I don't since I have specified the ./typings folder as one of my typeRoots but it's possible that I have configured it wrong somehow. Any thoughts on what I am doing wrong?

I am using TypeScript 2.2.1.

Upvotes: 1

Views: 1197

Answers (1)

artem
artem

Reputation: 51749

Directories used as typeRoots are supposed to look like node_modules directory, that is, your declaration file for foo should be in typings/foo folder and be named index.d.ts (or you should have package.json in typings/foo with types property pointing to the declaration file).

Upvotes: 2

Related Questions