如何 export/import a only a type definition in TypeScript

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

如何独立于模块本身导出和导入类型定义。

在 flowtype 中,它看起来像这样: 文件 sub.js 使用 export type myType = {id: number}; 导出类型 myType,文件 main.js 使用 import type {myType} from './sub.js';

导入类型

您只需正常导入它,编译器会计算出您不需要发出导入语句,因为没有使用具体代码。

这是一个例子:

component.ts

export interface MyInterface {
    name: string;
}

app.ts

import { MyInterface } from './component';

class MyClass implements MyInterface {
    constructor(public name: string) { }
}

app.js文件很简单(ES2015版本):

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

或者用旧的 ES5 术语来说:

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

这里重要的是 TypeScript 编译器已经计算出只在编译时需要导入,而不是运行时。

Typescript 3.8 及更高版本只有导出和导入类型:

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

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

export type { SomeThing };