【问题标题】:Convert nodejs-style export to typescript-style export将 nodejs 样式的导出转换为 typescript 样式的导出
【发布时间】:2020-05-23 12:27:39
【问题描述】:

所以,我会在 Node.js 中导出主要和“次要”功能:

module.exports = (amount) => {
  return amount
}

module.exports.calc = (amount) => {
  return amount * amount
}

module.exports.stringify = (amount) => {
  return String(amount)
}

然后像这样从其他文件中调用它:

const amountix = require('./amountix')

amountix(20) // 20
amountix.calc(20) // 400
amountix.stringify(20) // "20"

但现在我需要将此模块从 Node.js 转换为 TypeScript。我尝试了以下方法:

export default (amount: number): number => {
  return amount;
}

export function calc(amount: number): number {
  return amount * amount;
}

export function stringify(amount: number): string {
  return String(amount);
}

import * as amountix from "./amountix.ts"

amountix(20) // ERROR: This expression is not callable.
amountix.calc(20) // 400
amountix.stringify(20) // "20"

但是当我调用“主要”函数时它给了我错误。

我该如何以正确的方式做到这一点?

【问题讨论】:

    标签: javascript node.js typescript import


    【解决方案1】:
    import * as amountix from './amountix';
    
    // call the default method
    amountix.default(20);
    

    或者

    import amountix, { calc, stringify } from './amountix';
    
    amountix(20);
    

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 2018-06-12
      • 1970-01-01
      • 2019-11-24
      • 2018-08-17
      • 2020-09-22
      • 2017-09-23
      • 2016-12-09
      • 1970-01-01
      相关资源
      最近更新 更多