typescript 中 export interface 仅导出类型,不生成运行时代码;export class 同时导出值和类型;可使用 export type 或 import type 显式处理类型导入。

在 JavaScript(特别是 TypeScript 环境中)里,export 不能直接导出接口(interface),因为接口是纯类型层面的定义,编译后会被擦除;但可以导出类(class),它在运行时存在。不过 TypeScript 支持对类型(包括接口、类型别名、类等)进行“类型导出”,供其他文件做类型检查用。
✅ 导出类(运行时 + 类型都可用)
类既是值(可实例化),也是类型(可用来标注变量),所以用 export class 即可同时满足运行时使用和类型引用:
// math.ts
export class Calculator {
add(a: number, b: number): number {
return a + b;
}
}
在其他文件中可直接导入并使用:
// app.ts
import { Calculator } from './math';
const calc = new Calculator();
console.log(calc.add(2, 3)); // 5
✅ 导出接口(仅类型层面,需显式加 type 或依赖自动推导)
接口本身不生成 JS 代码,所以不能用 export interface 作为“值导出”,但 TypeScript 允许你写:
将一个或多个视频上传至YouTube。当用户想“上传到YouTube”“发YouTube”“批量上传”“upload to YouTube”“post videos to YouTube”或发布到YouTube时使用此技能。
// types.ts
export interface User {
id: number;
name: string;
}
这行代码是合法且常用的——它导出的是**类型**,不是值。只要你在导入处只把它用于类型位置(如类型注解、泛型参数),就不会报错:
// app.ts
import { User } from './types';
<p>function printUser(u: User) { /<em> ... </em>/ } // ✅ 正确:u 是类型位置
// const u: User = {}; // ❌ 若未定义任何值,会提示“无法找到名称 'User'”?不会,TypeScript 能识别类型导入</p><p>// 注意:下面这种写法在旧版 TS 可能需开启 <code>importsNotUsedAsValues</code>,但现代 TS(4.5+)默认支持自动类型导入
// 不需要额外写 <code>import type { User } from './types';</code>,除非你明确只想导入类型(避免误用为值)</p>
如果想**强制只作类型导入**(防止被当作值误用),可用 import type 或 export type:
-
export type { User };—— 显式导出类型(推荐用于类型别名或重导出) -
export interface User { ... }—— 等价于export type User = ...的语义,只是语法不同 - 导入时写
import type { User } from './types';—— 表明此处只取类型,TS 编译后完全不生成 import 语句
⚠️ 常见误区提醒
-
不能 new 一个接口:
const u = new User();❌ 接口无运行时实体 -
不能在值位置直接引用接口名:
const x: typeof User = ...;❌User不是值,没有typeof -
类可以同时当类型用:
let c: Calculator;✅ 类名自动提供类型;也可import type { Calculator } from './math';(更精确) -
默认导出也适用:
export default interface Config { ... }是允许的,导入用import Config from './config';(此时 Config 仅为类型)
? 小技巧:混合导出与类型重导出
比如你想把多个接口/类型统一从一个入口导出:
// index.ts
export { User } from './types'; // 导出类型(值导入语法,TS 自动识别)
export type { ApiResponse } from './api'; // 显式声明只导出类型
export { Calculator } from './math'; // 导出类(值 + 类型)










