在TypeScript中,组合不同类型可以通过多种方式实现,以满足不同的需求和场景。以下是一些常见的方法和示例:
交叉类型可以将多个类型合并为一个类型,使得新类型具有所有类型的特性。
示例:
interface Person {
name: string;
age: number;
}
interface Employee {
employeeId: number;
department: string;
}
type EmployeePerson = Person & Employee;
const emp: EmployeePerson = {
name: "John",
age: 30,
employeeId: 12345,
department: "Engineering"
};
联合类型表示一个值可以是几种类型之一。
示例:
type StringOrNumber = string | number;
function padLeft(value: string, padding: StringOrNumber) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
类型别名可以为现有类型创建一个新的名称。
示例:
type Name = string;
type Age = number;
interface Person {
name: Name;
age: Age;
}
泛型允许你编写可以在多种类型上工作的代码,而不是单一类型。
示例:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString");
let output2 = identity("myString"); // 类型推断
条件类型允许你根据某些条件选择不同的类型。
示例:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
映射类型允许你基于现有类型创建新类型,通常用于对现有类型的属性进行转换。
示例:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface Todo {
title: string;
description: string;
}
type ReadonlyTodo = Readonly<Todo>;
通过这些方法,你可以灵活地在TypeScript中组合和管理不同类型,从而编写出更健壮和可维护的代码。
领取专属 10元无门槛券
手把手带您无忧上云