如何只声明JS模块的一部分?

时间:2017-03-02 00:26:04

标签: typescript

我无法完全理解声明。如果我只想declare模块的一部分,这是否是正确的方法(忽略any的使用)?

import { Method as JaysonMethod } from 'jayson/promise';
declare class JaysonMethod {
  handler: any;
  execute(server: any, requestParams: any, callback: any) : void;
}

如果是这样,如果我希望声明在导入Method的其他模块中可用,该怎么办?如果我必须将声明放在.d.ts文件中,我是否必须始终使用别名Method导入JaysonMethod? TypeScript如何将声明与实际模块或其中的一部分进行匹配?

我真的很困惑,似乎无法找到一个好的解释。

1 个答案:

答案 0 :(得分:0)

简而言之,您可能会混淆变量及其类型。

import { Method as JaysonMethod } 'jayson/promise'未声明Method的类型,这是ES6中重命名命名导出的语法。

以下内容应该有效:

import { Method } from 'jayson/promise';

declare class JaysonMethod { ... }
const typedMethod: JaysonMethod = Method

// typedMethod is now typed.
// or
(Method as JaysonMethod)...

更新:根据您的需要,最好创建一个打字文件。类似的东西:

// custom-typings/jayson.d.ts
declare module 'jayson/promise' {
  export class Method { ... }
}

并将其添加到您的tsconfig.json

{
  "include": [ "custom-typings" ]
}