类型别名(Type Alias)是 TypeScript 中的一种特性,允许你为现有的类型创建一个新的名称。类型别名可以用于简化复杂类型的定义,提高代码的可读性和可维护性。类型别名不仅可以用于基本类型,还可以用于联合类型、交叉类型、元组类型等。
定义类型别名的基本语法
type AliasName = ExistingType;
示例
1. 基本类型别名
你可以为基本类型(如 string
、number
等)创建别名:
type StringAlias = string;
type NumberAlias = number;
let name: StringAlias = "Alice";
let age: NumberAlias = 25;
2. 联合类型别名
你可以为联合类型创建别名:
type StringOrNumber = string | number;
let value: StringOrNumber;
value = "hello"; // OK
value = 42; // OK
value = true; // Error: Type 'boolean' is not assignable to type 'StringOrNumber'.
3. 交叉类型别名
你可以为交叉类型创建别名:
type Person = {
name: string;
};
type Employee = {
employeeId: number;
};
type EmployeePerson = Person & Employee;
const employee: EmployeePerson = {
name: "Alice",
employeeId: 1234
};
4. 元组类型别名
你可以为元组类型创建别名:
type StringNumberPair = [string, number];
let pair: StringNumberPair = ["hello", 42];
5. 函数类型别名
你可以为函数类型创建别名:
type GreetFunction = (name: string) => string;
const greet: GreetFunction = function(name: string) {
return `Hello, ${name}!`;
};
console.log(greet("Alice")); // 输出: Hello, Alice!
6. 复杂类型别名
你可以为复杂的类型结构创建别名:
type ComplexType = {
id: number;
name: string;
details: {
age: number;
address: string;
};
};
const person: ComplexType = {
id: 1,
name: "Alice",
details: {
age: 25,
address: "123 Main St"
}
};
7. 泛型类型别名
你可以为泛型类型创建别名:
type Container<T> = { value: T };
const numberContainer: Container<number> = { value: 42 };
const stringContainer: Container<string> = { value: "hello" };
类型别名与接口的区别
虽然类型别名和接口在某些方面非常相似,但它们也有一些区别:
扩展性:
- 接口可以通过继承来扩展,而类型别名可以通过交叉类型来组合。
interface Person {
name: string;
}
interface Employee extends Person {
employeeId: number;
}
type Person = {
name: string;
};
type Employee = Person & {
employeeId: number;
};
重复定义:
- 接口可以重复定义,并且会自动合并,而类型别名不能重复定义。
interface Person {
name: string;
}
interface Person {
age: number;
}
const person: Person = {
name: "Alice",
age: 25
};
type Person = { // Error: Duplicate identifier 'Person'.
name: string;
};
使用场景:
- 接口通常用于描述对象的形状,而类型别名可以用于描述任何类型,包括基本类型、联合类型、交叉类型等。
总结
类型别名是 TypeScript 中用于为现有类型创建新名称的特性。它可以用于简化复杂类型的定义,提高代码的可读性和可维护性。类型别名适用于基本类型、联合类型、交叉类型、元组类型、函数类型等。理解类型别名的使用场景和与接口的区别,可以帮助你更好地利用 TypeScript 的类型系统,编写出更安全、更易维护的代码。