typescripttype-only-import-export

How to export/import a only a type definition in TypeScript


How can I export and import a type definition independently from the module itself.

In flowtype this would look like this: The file sub.js export the type myType using export type myType = {id: number}; and the file main.js imports the type using import type {myType} from './sub.js';


Solution

  • You just import it normally and the compiler works out that you don't need the import statement emitted because no concrete code is used.

    Here's an example:

    component.ts

    export interface MyInterface {
        name: string;
    }
    

    app.ts

    import { MyInterface } from './component';
    
    class MyClass implements MyInterface {
        constructor(public name: string) { }
    }
    

    The app.js file is simply (ES2015 version):

    class MyClass {
        constructor(name) {
            this.name = name;
        }
    }
    

    Or in older ES5 terms:

    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var MyClass = /** @class */ (function () {
        function MyClass(name) {
            this.name = name;
        }
        return MyClass;
    }());
    

    The important thing here is that the TypeScript compiler has worked out that the import is only needed at compile time, not runtime.