使用TypeScript导入自定义声明文件

时间:2017-03-01 16:50:28

标签: javascript typescript visual-studio-code

对于名为foo的npm包,我有以下TypeScript声明(我只是假设为了这个例子)我没有任何可以提取的声明文件。

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

我已将该声明放在./typings/foo.d.ts文件中,并将我的typeRoots文件夹更新到下面(./tsconfig.json文件内):

{
    "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"
    ]
}

我尝试在.ts下面使用它:

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

然而,它无法解决这个问题。它也在VS Code中向我抱怨(因为我有noImplicitAny: true,我想,考虑this)。

我已经将我的消费改为下面了,结果很明显:

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

我真的需要reference声明吗?我期待我没有,因为我已将./typings文件夹指定为typeRoots之一,但我可能会以某种方式将其配置错误。对我做错了什么的想法?

  

我使用的是TypeScript 2.2.1。

1 个答案:

答案 0 :(得分:0)

用作typeRoots的目录应该看起来像node_modules目录,也就是说,foo的声明文件应该在typings/foo文件夹中并命名为{{1 (或者index.d.tspackage.json typings/footypes属性指向声明文件。)