typescript - 相当于 Typescript 声明文件中的 module.exports

标签 typescript

我尝试做一个库的声明文件。

library.js 文件中有:

if (typeof module !== 'undefined' /* && !!module.exports*/) {
    module.exports = Library;
}

我应该在我的 library.d.ts 文件中放入什么才能在我的代码中导入和使用这个库?

我希望能够做到:

import { Library } from 'library';
const instance = new Library();

最佳答案

正如@Nitzan 所指出的,您需要使用特殊的 export =import Library = require 语法:

export = and import = require()


一个完整的例子:

node_modules/library/index.js

module.exports = function(arg) {
  return 'Hello, ' + arg + '.';
}

library.d.ts 这个文件名在技术上并不重要,只有 .d.ts 扩展名。

declare module "library" {
  export = function(arg: string): string;
}

source.ts

import Library = require('library');

Library('world') == 'Hello, world.';

关于typescript - 相当于 Typescript 声明文件中的 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41496915/

相关文章:

reactjs - 基于其他 Prop 值(value)的条件类型

typescript - 在 VSCode 中调试 lerna-typescript 项目

带有可选参数的 TypeScript lambda 函数

javascript - JavaScript new Date() 使用什么时区?

javascript - 为任何 Function React Typescript 定义 prop 的类型

用于推断的 never[] 和 any[] 的 Typescript UnpackArrayType 工作不正确

typescript - ESLint 在包含的 tsconfig 文件上抛出错误

typescript - 推断函数的参数列表

reactjs - 如何正确定义样式组件(对于 TypeScript)的引用(React.RefObject<StyledComponentClass>)?

reactjs - 如何避免在 redux thunk 中使用单独的 _PENDING _FULFILLED 和 _REJECTED 操作?