Search code examples
javascripttypescriptdefault

Typescript export default function


My current typescript version is 1.6.2 and we compile it to ECMA 5. I am new to TypeScript so please be understanding. These are the imported library typings.

redux-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;
}

In app.ts:

import thunk from "redux-thunk";

console.log(thunk);

I am getting undefined. This is the code taken from: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/redux-thunk/redux-thunk-tests.ts (7 and 16 lines)

I've got the same problem with all libraries that uses default import in typescript.

EDIT: @Steve Fenton I am using npm to do the job for me. I've just noticed that the problem is with Typescript compiler. When I create typescript file with export default function I get for example:

Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
    nextQuestion: nextQuestion,
};

Notice exports.default

When I look into redux-thunk.js file downloaded from npm there is:

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'];

Notice module.exports = exports['default'];

If I take redux-thunk typings into Babel compiler I get the results with exports['default'] style.

The most important part is that when I replace export['default'] style to exports.default style in redux-thunk.js then everything works. Is this a problem with my compiler?


Solution

  • My friend just got the answer on github: https://github.com/Microsoft/TypeScript/issues/5565#issuecomment-155216760

    ahejlsberg answer: It appears the "redux-logger" module was transpiled with Babel. When Babel transpiles a module whose only export is an export default it injects a module.exports = exports["default"]; into the generated code, causing the exported object to become the function itself (instead of a module object that has the function as the default property). When paired with the _interopRequireDefault magic that Babel generates for imports the net effect is that a fake module object with a default property is created and the function can now be accessed as _reduxLogger2.default.

    TypeScript doesn't do any of this magic (see here for more details). In order for TypeScript to consume the module you need to change the redux-logger.d.ts declaration file to actually reflect what is going on