首页 > 解决方案 > TypeScript - What does importing and exporting interfaces as type do?

问题描述

The TS docs mention interfaces and type aliases, but I can't seem to find much info on importing or exporting interfaces as type and was hoping to get some clarification:

For example an interface can be exported as:

// located in ./MyInterface.ts
export interface MyInterface
{
    foo: string;
    bar: () => number;
}

export type {MyInterface as MyInterfaceType}

and it can be imported as:
import {MyInterface} from "./MyInterface"
or
import type {MyInterface} from "./MyInterface"
or
import {MyInterfaceType} from "./MyInterface"
or
import type {MyInterfaceType} from "./MyInterface"

Can anyone explain the difference in behavior between each interface import?

标签: typescripttypesimportinterfaceexport

解决方案


TypeScript 3.8 为仅类型导入和导出添加了新语法

export type { MyInterface as MyInterfaceType }

仅导出MyInterface带别名的类型MyInterfaceType

export type仅提供可用于类型上下文的导出,并且也从 TypeScript 的输出中删除。

export interface MyInterface
{
    foo: string;
    bar: () => number;
}

这是一个名为 export 的 ECMAScript 2015 模块。

从 ECMAScript 2015 开始,JavaScript 有了模块的概念。TypeScript 共享这个概念。

任何声明(例如变量、函数、类、类型别名或接口)都可以通过添加 export 关键字来导出。

请参阅导出声明


推荐阅读