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

7.8k views Asked by At

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

2

There are 2 answers

0
Fenton On BEST ANSWER

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.

0
kmui2 On

Typescript 3.8 and later has type only exports and imports:

https://devblogs.microsoft.com/typescript/announcing-typescript-3-8/#type-only-imports-exports

import type { SomeThing } from "./some-module.js";

export type { SomeThing };