Why are my typescript interfaces being compiled to javascript?

Viewed 2309

As I understand it, interfaces are only relevant in Typescript and the tsc compiler should be smart enough not to convert them to JS files in the final output. When I compile my code the interfaces are being compiled with it. Why is this?

My simplified project structure

src/
  index.ts
  lib/
    EventClient.ts
  interfaces/
    EventClientConfig.ts

What it compiles to

dist/
  index.js
  lib/
    EventClient.js
  interfaces/
    EventClientConfig.js

My tsconfig.json

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "outDir": "./dist",
    "lib": ["ES6", "DOM"],
    "target": "ES2018",
    "module": "CommonJS",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "removeComments": true,
    "strict": true,
    "typeRoots": ["./node_modules/@types"],
    "rootDir": "./src",
    "types": [
      "node",
      "jest-fetch-mock",
      "express",
      "reflect-metadata"
    ]
  },
  "include": ["src"],
  "exclude": ["dist", "node_modules", "**/*spec.ts"]
}

An interface

export interface EventClientConfig {
  endpoint: string;
  authToken: string;
}

How I'm using the interface

import { EventClientConfig } from '../interfaces/EventClientConfig';

const config: EventClientConfig = {
  endpoint: '/api',
  authToken: '123456'
}

What the interface is compiled to

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

In the compiled code EventClient.js makes no actual reference to the EventClientConfig.js so it's definitely not required. Why is Typescript compiling the interface files to JS?

2 Answers

This was solved thanks to @AluanHaddad who suggested using .d.ts declaration files. I have changed all my interface filenames so that they end with .d.ts and they are no longer included in the output.

The answer to your questions is here modules

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

Related