TypeScript:如何为已安装的npm包定义自定义类型?

时间:2016-06-05 12:33:35

标签: node.js typescript typescript1.8

我喜欢在TypeScript中使用rx-node

import RxNode from 'rx-node';

我使用npm

安装了rx-node
$ npm install rx-node --save

我搜索了类型定义,但没有任何结果

$ typings search rx-node
No results found for search

如何为已安装的npm模块rx-node定义自定义类型定义?我应该在哪里存储类型定义文件?如何配置TypeScript( tsconfig.json typings.json )?

修改:感谢Aleksey L.David Bohunek我完成了定义rx-node.d.ts,看起来像这样

declare module "rx-node" {
  import {Observable} from '@reactivex/rxjs';
  import {ReadLine} from "readline";

  function fromReadLineStream(stream: ReadLine): Observable<string>
}

我安装了@reactivex/rxjs

npm install --save @reactivex/rxjs

因为我收到了错误

node_modules\@reactivex\rxjs\dist\cjs\Observable.d.ts (10,66): Cannot find name 'Promise'. (2304)

我将 tsconfig.json 中的目标更改为es6

3 个答案:

答案 0 :(得分:34)

您可以将自定义定义添加到 typings.json 。例如,具有以下文件夹结构:

/typings
    /custom
        rx-node.d.ts
    /global
        ...

其中rx-node.d.ts是您的自定义打字文件。例如:

declare module RxNode {
    export interface ...
}

然后使用命令安装

typings install file:typings/custom/rx-node.d.ts --save --global

或手动:在 typings.json 中添加对此打字文件的引用:

{
    "name": "TestName",
    "version": false,
    "globalDependencies": {
        "rx-node": "file:typings/custom/rx-node.d.ts"
    }
}

并运行typings install

答案 1 :(得分:1)

创建一个名为rx-node.d.ts的新文件,并确保在tsconfig.json中直接或从其他文件引用该文件,例如typings/index.d.ts。 然后你可以从这样的事情开始:

///<reference path="rx.d.ts" />

declare namespace RxNode  {

    export interface Emitter<T>{

    }

    export function toEventEmitter<T>(observable: Rx.Observable<T>, eventName: string): Emitter<T>;
}

这个问题/答案可能有用:How to write d.ts file from existing .js file?

如果您创建一个漂亮的高质量打字定义文件,请提供https://github.com/DefinitelyTyped/DefinitelyTyped

答案 2 :(得分:0)

对于使用create-react-app(反应脚本)的ReactJS项目,您可以在src/react-app-env.d.ts中为未类型化的包添加模块声明。

declare module "not-typed";

注意:以后该文件的位置可能会更改,请参见this issue