在 TypeScript 中,可以使用 import type
导入各种类型定义。以下是一些可以通过 import type
导入的内容:
-
类型别名(Type Aliases):
- 使用
type
定义的别名。
// types.ts export type User = { name: string; age: number; }; // main.ts import type { User } from './types';
- 使用
-
接口(Interfaces):
- 使用
interface
定义的类型。
// types.ts export interface IUser { name: string; age: number; }; // main.ts import type { IUser } from './types';
- 使用
-
枚举(Enums):
- 定义的枚举类型。
// enums.ts export enum Color { Red, Green, Blue, } // main.ts import type { Color } from './enums';
-
元组(Tuples):
- 定义的元组类型。
// types.ts export type Point = [number, number]; // main.ts import type { Point } from './types';
-
联合类型(Union Types)与交叉类型(Intersection Types):
- 可以定义和使用联合或交叉类型。
// types.ts export type Status = 'active' | 'inactive'; export type UserStatus = User & { status: Status }; // main.ts import type { UserStatus } from './types';
-
函数类型:
- 可以导入已定义函数签名的类型。
// types.ts export type Callback = (data: string) => void; // main.ts import type { Callback } from './types';
功能与优势
- 避免引入运行时依赖: 使用
import type
不会将实际模块引入编译后的 JavaScript,因此没有运行时的依赖关系。 - 提高代码可读性: 使得代码的意图更加明确,特别是对于大型项目,其他开发者可以快速识别哪些导入是用于类型检查的。
- 优化编译结果: 减少最终生成代码的大小,因不引入未使用的运行时代码。
总结
总而言之,任何在 TypeScript 中定义的类型(如类型别名、接口、枚举等)都可以使用 import type
导入。这种导入方式让开发者可以专注于类型安全,同时保持代码整洁和高效。