方法一:使用 export
导出类型定义
- 描述:在定义类型(如接口或类型别名)的文件中,使用
export
关键字将其导出,然后在其他模块中通过 import
导入使用。
- 示例:
// types.ts
export interface User {
name: string;
age: number;
}
export type Role = 'admin' | 'user' | 'guest';
- **使用共享类型的文件 `main.ts`**
// main.ts
import { User, Role } from './types';
const user: User = { name: 'John', age: 30 };
const role: Role = 'user';
方法二:使用声明文件 .d.ts
- 描述:创建一个声明文件(
.d.ts
),在其中定义共享类型。在TypeScript项目中,编译器会自动查找这些声明文件。对于非TypeScript模块(如JavaScript模块),这种方式也能很好地为其提供类型定义。
- 示例:
// shared.d.ts
export interface Product {
id: number;
title: string;
price: number;
}
- **使用共享类型的文件 `app.ts`**
// app.ts
import { Product } from './shared';
const product: Product = { id: 1, title: 'Book', price: 10 };
方法三:使用命名空间(内部模块)
- 描述:在TypeScript中,命名空间(内部模块)可以用于组织代码和共享类型。通过将相关的类型定义放在一个命名空间内,并使用
export
控制其可见性,不同模块可以共享这些类型。
- 示例:
// utils.ts
namespace Shared {
export interface Point {
x: number;
y: number;
}
export function distance(p1: Point, p2: Point): number {
return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y));
}
}
export { Shared };
- **使用命名空间内类型的文件 `geometry.ts`**
// geometry.ts
import { Shared } from './utils';
const point1: Shared.Point = { x: 0, y: 0 };
const point2: Shared.Point = { x: 3, y: 4 };
const dist = Shared.distance(point1, point2);