Ekmek
Ekmek

Reputation: 481

How to wrap an interface in an object while exporting it in TypeScript?

I have a file called x.ts, here is what it holds:

interface x {
  x: string;
}
interface y{
  x: string;
}
interface z {
  x: string;
}
interface i{
  x: string;
}

I want to export the interfaces like this:

export = {
   a: {
      x,
      y
   },
   b: {
      z,
      i
   }
}

How can I do this in TypeScript?

Upvotes: 2

Views: 970

Answers (1)

Objects (every value in JavaScript / TypeScript) can contain only values as properties (methods, constants, properties) which interfaces are not. But don't worry, there's the way! Its name is namespaces.

export namespace a {
   export interface x {
      x: string;
   }
   export interface y{
      x: string;
   }
}

export namespace b {
    export interface z {
       x: string;
    }
    export interface i{
       x: string;
    }
}

See TypeScript docs for more info.

Secondly

I recommend using ECMAScript modules, not CommonJS. If you use a normal TypeScript compiler, TypeScript automatically compiles to Node.js modules. You used it in the import but not in the export. Don't use export = {}. See TypeScript Docs for more.

In tsconfig.json:

{
    "compilerOptions": {
        // ...
        "moduleResolution": "node",
        "module": "commonjs"
    }
}

And then import {a, b} from "./x.ts"

Upvotes: 3

Related Questions