Typescript导出默认功能

Mis*_*tyK 2 javascript default typescript

我当前的打字稿版本是1.6.2,我们将它编译为ECMA 5.我是TypeScript的新手,所以请理解.这些是导入的库类型.

终极版,thunk.d.ts:

    declare module "redux-thunk" {
    import { Middleware, Dispatch } from 'redux';

    export interface Thunk extends Middleware { }

    export interface ThunkInterface {
        <T>(dispatch: Dispatch, getState?: () => T): any;
    }

    var thunk: Thunk;

    export default thunk;
}
Run Code Online (Sandbox Code Playgroud)

在app.ts:

import thunk from "redux-thunk";

console.log(thunk);
Run Code Online (Sandbox Code Playgroud)

我没有定义.这段代码来自:https: //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/redux-thunk/redux-thunk-tests.ts (7和16行)

对于在打字稿中使用默认导入的所有库,我遇到了同样的问题.

编辑:@Steve Fenton我正在使用npm为我做这份工作.我刚才注意到问题出在Typescript编译器上.当我使用导出默认函数创建typescript文件时,我得到例如:

Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
    nextQuestion: nextQuestion,
};
Run Code Online (Sandbox Code Playgroud)

注意 exports.default

当我查看redux-thunk.js从npm下载的文件时,有:

exports.__esModule = true;
exports['default'] = thunkMiddleware;

function thunkMiddleware(_ref) {
    var dispatch = _ref.dispatch;
    var getState = _ref.getState;

    return function (next) {
        return function (action) {
            return typeof action === 'function' ? action(dispatch, getState) : next(action);
        };
    };
}

module.exports = exports['default'];
Run Code Online (Sandbox Code Playgroud)

注意 module.exports = exports['default'];

如果我将redux-thunk打字输入Babel编译器,我会得到带有exports['default']样式的结果.

最重要的部分是,当我将export['default'] 样式替换为exports.default 样式时, redux-thunk.js一切都有效.这是我的编译器的问题吗?

Mis*_*tyK 6

我的朋友刚刚在github上得到了答案:https: //github.com/Microsoft/TypeScript/issues/5565#issuecomment-155216760

ahejlsberg回答:看来"redux-logger"模块是用Babel编译的.当Babel转换出一个模块,其唯一的导出是导出默认值时,它会注入一个module.exports = exports ["default"]; 生成的代码,导致导出的对象成为函数本身(而不是具有该函数作为默认属性的模块对象).当与Babel为导入生成的_interopRequireDefault魔法配对时,净效果是创建具有默认属性的伪模块对象,现在可以将该函数作为_reduxLogger2.default进行访问.

TypeScript没有做任何这种魔术(有关更多详细信息,请参见此处).为了让TypeScript使用模块,您需要更改redux-logger.d.ts声明文件以实际反映正在发生的事情