【问题标题】:How to use es6 syntax to import a function module in TypescriptTypescript中如何使用es6语法导入功能模块
【发布时间】:2016-12-22 06:43:34
【问题描述】:

我有一个简单的模块。用于检查变量类型。

index.js

'use strict';
var typeOf = function (variable) {
    return ({}).toString.call(variable).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};
module.exports = typeOf;

index.d.ts

export default typeOf;
declare function typeOf(value:any):string;

这里是我如何使用它。

import typeOf from 'lc-type-of';
typeOf(value);

但代码并没有按预期工作。 typeOf 函数出现未定义的错误。我错过了什么吗?

【问题讨论】:

    标签: javascript typescript ecmascript-6 es6-modules


    【解决方案1】:

    当您像使用 Javascript 一样导出节点时:

    module.exports = something;
    

    在 Typescript 中像这样导入它:

    import * as something from "./something"
    

    在定义中

    // Tell typescript about the signature of the function you want to export
    declare const something: ()=> void ;
    
    // tell typescript how to import it     
    declare module something {
          // Module does Nothing , it simply tells about it's existence
    }
    
    // Export 
    export =  something;
    

    【讨论】:

    • 我按你说的改了。但是编译器说error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "E:/project/node_modules/lc-type-of/index"' has no compatible call signatures.
    • 添加您的添加代码后。现在可以了!好厉害的小伙伴!谢谢。
    • 我能问你为什么我必须声明一个模块吗?它只是一个函数。
    • 如果它不是模块,你将如何导入它? :)
    • 您实际上可以只导出函数@Dan! :)
    猜你喜欢
    • 2015-07-27
    • 2019-07-06
    • 2015-08-13
    • 2018-02-06
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 2016-07-14
    • 2018-11-01
    相关资源
    最近更新 更多