【TypeScript】TS交叉类型

TypeScript 中的交叉类型(Intersection Types)是一种强大的类型构造,允许多个类型组合成一个新类型,新类型将具有所有原类型的特性。交叉类型使用 & 运算符来定义,以下是详细介绍和几个示例:

定义

交叉类型使用 & 运算符将多个类型合并在一起,如下所示:

typescript 复制代码
type Type1 = { property1: number };
type Type2 = { property2: string };

type CombinedType = Type1 & Type2;

在上面的示例中,CombinedTypeType1Type2 的交叉类型,它具有 property1property2 两个属性。

合并对象类型

typescript 复制代码
type Person = { name: string; age: number };
type Address = { street: string; city: string };

type PersonWithAddress = Person & Address;

const personWithAddress: PersonWithAddress = {
  name: 'John',
  age: 30,
  street: '123 Main St',
  city: 'Example City'
};

上述示例中,PersonWithAddress 类型合并了 PersonAddress 类型,生成了一个包含姓名、年龄、街道和城市属性的新类型。

组合函数类型

typescript 复制代码
type MathFunction = (x: number) => number;
type StringFunction = (s: string) => string;

type CombinedFunction = MathFunction & StringFunction;

const combinedFunc: CombinedFunction = (arg) => arg.toString();

const result = combinedFunc(42); // 返回字符串 "42"

在这个示例中,CombinedFunctionMathFunctionStringFunction 的交叉类型,这允许 combinedFunc 接受一个数字并返回它的字符串表示。

合并类类型

typescript 复制代码
class Dog {
  bark() {
    console.log('Woof! Woof!');
  }
}

class Robot {
  move() {
    console.log('Walking...');
  }
}

type PetRobot = Dog & Robot;

const petRobot = new PetRobot();
petRobot.bark();  // 输出 "Woof! Woof!"
petRobot.move();  // 输出 "Walking..."

在这个示例中,PetRobot 类型是 DogRobot 类型的交叉类型,所以 petRobot 实例既能够叫也能够行走。

合并接口类型

typescript 复制代码
interface Employee {
  name: string;
  jobTitle: string;
}

interface Manager {
  department: string;
}

type ManagerEmployee = Employee & Manager;

const managerEmployee: ManagerEmployee = {
  name: 'Alice',
  jobTitle: 'Manager',
  department: 'HR'
};

在这个示例中,ManagerEmployee 类型是 EmployeeManager 接口的交叉类型,它包含了员工的名称、工作标题和经理的部门。

合并枚举类型

typescript 复制代码
enum Color {
  Red = 'RED',
  Green = 'GREEN',
  Blue = 'BLUE'
}

enum Size {
  Small = 'SMALL',
  Medium = 'MEDIUM',
  Large = 'LARGE'
}

type ColorSize = Color & Size;

const myChoice: ColorSize = 'REDMEDIUM';

在这个示例中,ColorSize 类型是 ColorSize 枚举的交叉类型。您可以将颜色和尺寸组合在一起,例如 'REDMEDIUM'

合并混合类型

typescript 复制代码
type Printable = {
  print: () => void;
};

type Serializable = {
  serialize: () => string;
};

type Document = Printable & Serializable;

const document: Document = {
  print: () => console.log('Printing...'),
  serialize: () => 'Serialized data'
};

document.print();        // 输出 "Printing..."
const serialized = document.serialize();
console.log(serialized); // 输出 "Serialized data"

在这个示例中,Document 类型是 PrintableSerializable 类型的交叉类型,它可以打印和序列化文档对象。

这些示例展示了如何使用交叉类型将不同类型的特性合并到一个新的类型中,以满足特定需求。交叉类型是 TypeScript 中强大的类型工具,用于创建复杂、多功能的类型定义。

相关推荐
菜鸟una7 小时前
【瀑布流大全】分析原理及实现方式(微信小程序和网页都适用)
前端·css·vue.js·微信小程序·小程序·typescript
还是大剑师兰特13 小时前
TypeScript 面试题及详细答案 100题 (71-80)-- 模块与命名空间
前端·javascript·typescript
一点七加一13 小时前
Harmony鸿蒙开发0基础入门到精通Day01--JavaScript篇
开发语言·javascript·华为·typescript·ecmascript·harmonyos
还是大剑师兰特14 小时前
TypeScript 面试题及详细答案 100题 (61-70)-- 泛型(Generics)
typescript·大剑师·typescript教程·typescript面试题
Linsk16 小时前
为什么BigInt无法通过Babel降级?
前端·typescript·前端工程化
濮水大叔18 小时前
VonaJS AOP编程:魔术方法
typescript·nodejs·nestjs
Mintopia18 小时前
🧩 TypeScript防御性编程:让Bug无处遁形的艺术
前端·typescript·函数式编程
菜鸟una20 小时前
【微信小程序 + map组件】自定义地图气泡?原生气泡?如何抉择?
前端·vue.js·程序人生·微信小程序·小程序·typescript
孟陬1 天前
面试常见问题 TS 的 infer 你会用吗?对象如何转 snake_case
typescript
guangzan1 天前
解决 Semi Design Upload 组件实现自定义压缩,上传文件后无法触发 onChange
typescript·semi design