Jacek Wojcik
Jacek Wojcik

Reputation: 1273

TypeScript: Exporting complex interface

please have a look at code below:

enum ActionTypeEnum {
  GET_WAREHOUSE_ITEM_LIST_INITIAL = 'GET_WAREHOUSE_ITEM_LIST_INITIAL',
  GET_BASKET = 'GET_BASKET',
}    
interface Action {
    type: ActionTypeEnum,
}

export {ActionTypeEnum};  // works fine
export {Action};          //Cannot re-export a type when the '--isolatedModules' flag is provided.

As far as I understand it is possible to export ActionTypeEnum because it does not depend on anything.
As far as I understand it is not possible to export Action because it uses ActionTypeEnum and cannot be exported on it's own.

Please tell me how to export Action and if my understanding of the problem is correct.

Thank you! :-)

Upvotes: 2

Views: 197

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141792

This GitHub issue explores the topic. The compiler complains when:

  1. we use isolatedModules and
  2. we use export { SomeThing } with either a type or an interface.

This happens because, with isolated modules, each module is isolated, which makes it hard for transpilers like babel to decide whether SomeThing has a JavaScript representation. If SomeThing is a class, a function, or an object, then the transpiler needs to represent it in JavaScript. On the other hand, if SomeThing is a type or an interface, then the transpiler must not represent it in JavaScript.

What to do?

One option is an inline export interface SomeThing { } statement like this:

enum ActionTypeEnum1 {
  // ...
}

export interface Action1 { // <-------- inline export
  type: ActionTypeEnum1;
}

export { ActionTypeEnum1 };

If you are using TypeScript 3.8+, another option is to use export type { SomeThing } like this:

enum ActionTypeEnum2 {
  // ...
}

interface Action2 {
  type: ActionTypeEnum2;
}

export type { Action2 } // <-------- export type { }
export { ActionTypeEnum2 }

Upvotes: 3

Related Questions