TypeScript类型别名 #
一、类型别名基础 #
1.1 什么是类型别名 #
类型别名使用type关键字为类型创建新名称。它不会创建新类型,只是给现有类型起一个新名字。
typescript
type Name = string;
type Age = number;
type ID = string | number;
let name: Name = 'TypeScript';
let age: Age = 12;
let id: ID = 'abc123';
id = 123;
1.2 基本语法 #
typescript
type AliasName = Type;
二、基本类型别名 #
2.1 原始类型 #
typescript
type StringType = string;
type NumberType = number;
type BooleanType = boolean;
2.2 字面量类型 #
typescript
type Direction = 'up' | 'down' | 'left' | 'right';
type Status = 'pending' | 'approved' | 'rejected';
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
let dir: Direction = 'up';
let status: Status = 'pending';
let digit: Digit = 5;
2.3 联合类型 #
typescript
type ID = string | number;
type Result = string | number | boolean;
type EventName = 'click' | 'scroll' | 'mousemove';
function process(id: ID): void {
if (typeof id === 'string') {
console.log(id.toUpperCase());
} else {
console.log(id.toFixed(2));
}
}
2.4 交叉类型 #
typescript
type Name = { name: string };
type Age = { age: number };
type Email = { email: string };
type User = Name & Age & Email;
const user: User = {
name: 'TypeScript',
age: 12,
email: 'ts@example.com'
};
三、对象类型别名 #
3.1 基本对象类型 #
typescript
type User = {
name: string;
age: number;
email?: string;
};
const user: User = {
name: 'Alice',
age: 25
};
3.2 索引签名 #
typescript
type StringMap = {
[key: string]: string;
};
type NumberMap = {
[key: number]: string;
};
const map: StringMap = {
name: 'TypeScript',
version: '5.4'
};
3.3 方法类型 #
typescript
type Greet = (name: string) => string;
type Compare = (a: number, b: number) => number;
const greet: Greet = (name) => `Hello, ${name}!`;
const compare: Compare = (a, b) => a - b;
3.4 构造签名 #
typescript
type Constructor<T> = {
new (...args: any[]): T;
};
function createInstance<T>(ctor: Constructor<T>): T {
return new ctor();
}
四、数组与元组类型别名 #
4.1 数组类型 #
typescript
type NumberArray = number[];
type StringArray = string[];
type UserArray = User[];
type GenericArray<T> = Array<T>;
4.2 只读数组 #
typescript
type ReadonlyNumberArray = readonly number[];
type ReadonlyStringArray = ReadonlyArray<string>;
4.3 元组类型 #
typescript
type Point = [number, number];
type Point3D = [number, number, number];
type NamedTuple = [name: string, age: number];
type OptionalTuple = [string, number?];
type RestTuple = [string, ...number[]];
五、函数类型别名 #
5.1 函数类型 #
typescript
type Callback = (data: string) => void;
type AsyncFunction = () => Promise<void>;
type EventHandler = (event: Event) => void;
const callback: Callback = (data) => {
console.log(data);
};
5.2 函数重载类型 #
typescript
type OverloadedFunction = {
(x: string): string;
(x: number): number;
};
const fn: OverloadedFunction = (x: string | number) => x;
5.3 构造函数类型 #
typescript
type AnimalConstructor = {
new (name: string): Animal;
};
interface Animal {
name: string;
}
六、泛型类型别名 #
6.1 泛型基础 #
typescript
type Box<T> = {
value: T;
};
type Container<T> = {
data: T;
timestamp: number;
};
const stringBox: Box<string> = { value: 'hello' };
const numberContainer: Container<number> = { data: 42, timestamp: Date.now() };
6.2 多泛型参数 #
typescript
type Pair<K, V> = {
key: K;
value: V;
};
type Map<K, V> = {
[key: string]: Pair<K, V>;
};
const pair: Pair<string, number> = { key: 'age', value: 25 };
6.3 泛型约束 #
typescript
type WithLength<T extends { length: number }> = {
value: T;
length: number;
};
const str: WithLength<string> = { value: 'hello', length: 5 };
const arr: WithLength<number[]> = { value: [1, 2, 3], length: 3 };
6.4 泛型默认值 #
typescript
type ApiResponse<T = any> = {
code: number;
message: string;
data: T;
};
const response: ApiResponse = { code: 200, message: 'OK', data: 'success' };
const userResponse: ApiResponse<User> = {
code: 200,
message: 'OK',
data: { name: 'Alice', age: 25 }
};
七、映射类型别名 #
7.1 基础映射类型 #
typescript
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Partial<T> = {
[P in keyof T]?: T[P];
};
type Required<T> = {
[P in keyof T]-?: T[P];
};
interface User {
name: string;
age?: number;
}
type ReadonlyUser = Readonly<User>;
type PartialUser = Partial<User>;
type RequiredUser = Required<User>;
7.2 键重映射 #
typescript
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
7.3 过滤属性 #
typescript
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
interface Mixed {
name: string;
age: number;
email: string;
active: boolean;
}
type StringProps = OnlyStrings<Mixed>;
八、条件类型别名 #
8.1 条件类型基础 #
typescript
type IsString<T> = T extends string ? true : false;
type A = IsString<string>;
type B = IsString<number>;
8.2 infer关键字 #
typescript
type UnwrapArray<T> = T extends (infer U)[] ? U : T;
type Str = UnwrapArray<string[]>;
type Num = UnwrapArray<number>;
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type Result = UnwrapPromise<Promise<string>>;
8.3 条件类型分发 #
typescript
type ToArray<T> = T extends any ? T[] : never;
type StrArr = ToArray<string>;
type NumArr = ToArray<number>;
type Mixed = ToArray<string | number>;
九、模板字面量类型别名 #
9.1 基本用法 #
typescript
type EventName = `on${Capitalize<string>}`;
type ClickEvent = 'onClick';
type FocusEvent = 'onFocus';
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiEndpoint = `/api/${string}`;
9.2 结合映射类型 #
typescript
type EventHandlers<T> = {
[K in keyof T as `on${Capitalize<string & K>}`]: (event: T[K]) => void;
};
interface Events {
click: MouseEvent;
focus: FocusEvent;
blur: FocusEvent;
}
type Handlers = EventHandlers<Events>;
十、类型别名vs接口 #
10.1 相似之处 #
typescript
type UserType = {
name: string;
age: number;
};
interface UserInterface {
name: string;
age: number;
}
const user1: UserType = { name: 'Alice', age: 25 };
const user2: UserInterface = { name: 'Bob', age: 30 };
10.2 类型别名的优势 #
联合类型 #
typescript
type ID = string | number;
type Status = 'pending' | 'approved' | 'rejected';
元组类型 #
typescript
type Point = [number, number];
type RGB = [number, number, number];
映射类型 #
typescript
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
条件类型 #
typescript
type NonNullable<T> = T extends null | undefined ? never : T;
10.3 接口的优势 #
声明合并 #
typescript
interface Window {
customProp: string;
}
interface Window {
anotherProp: number;
}
extends继承 #
typescript
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
implements实现 #
typescript
interface Printable {
print(): void;
}
class Document implements Printable {
print() {}
}
10.4 选择建议 #
| 场景 | 推荐 |
|---|---|
| 对象类型 | interface |
| 联合类型 | type |
| 元组类型 | type |
| 映射类型 | type |
| 条件类型 | type |
| 需要扩展 | interface |
| 需要合并 | interface |
十一、实用类型别名示例 #
11.1 API类型 #
typescript
type ApiResponse<T = any> = {
code: number;
message: string;
data: T;
timestamp: number;
};
type PaginatedResponse<T> = ApiResponse<{
items: T[];
total: number;
page: number;
pageSize: number;
}>;
11.2 工具类型 #
typescript
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
type PickByType<T, U> = {
[P in keyof T as T[P] extends U ? P : never]: T[P];
};
11.3 函数工具类型 #
typescript
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type FirstParameter<T extends (...args: any) => any> = Parameters<T>[0];
十二、总结 #
本章介绍了TypeScript类型别名:
类型别名特点 #
- 为类型创建新名称
- 支持联合类型、交叉类型
- 支持泛型、映射类型、条件类型
- 更灵活的类型组合
与接口的区别 #
- 类型别名更灵活,支持更多类型
- 接口支持扩展和合并
- 对象类型优先使用接口
- 复杂类型使用类型别名
最佳实践 #
- 合理命名类型别名
- 使用泛型提高复用性
- 结合映射类型和条件类型
- 根据场景选择type或interface
最后更新:2026-03-26