TypeScript 学习 -类型 - 8

交叉类型 与 联合类型

交叉类型
ts 复制代码
interface DogInterface {
  run(): void;
}

interface CatInterface {
  jump(): void;
}

let pet: DogInterface & CatInterface = {
  run() {},
  jump() {},
};
联合类型
  • 只能访问公共的方法
  • 约束不可以漏处理某个类型
ts 复制代码
type Shape = Square | Rectangle | Circle;

// 约束不可以漏处理某个类型
// 如果 case 有遗漏, 会报错
function area(s: Shape) {
  switch (s.kind) {
    case "square":
      return s.size * s.size;
    case "rectangle":
      return s.height * s.width;
    case "circle":
      return Math.PI * s.r ** 2;
    default:
      // 如果可以走到 default , 则会判断传入的参数是不是 never 类型, 如果 case 有遗漏, 会报错
      return ((e: never) => {
        throw new Error(e);
      })(s);
  }
}

索引类型

  • Readonly 只读
  • Partial 可选
  • Pick 抽取部分属性
  • Record 创建一些新的属性
ts 复制代码
// 约束 keys 的类型
interface Obj {
  a: string;
  b: number;
  c: boolean;
}
// 把所有的属性变成只读
type ReadonlyObj = Readonly<Obj>;

var a: ReadonlyObj = {
  a: 'a',
  b: 1,
  c: true,
};

// 把所有的属性变成可选
type PartialObj = Partial<Obj>;

var b: PartialObj = {
  a: 'a',
};

// 抽取部分属性
type PickObj = Pick<Obj, 'a' | 'b'>;
var c: PickObj = {
  a: 'a',
  b: 1,
};

// 创建一些新的属性
type RecordObj = Record<'x' | 'y', Obj>;
var d: RecordObj = {
  x: {
    a: 'a',
    b: 1,
    c: true,
  },
  y: {
    a: 'b',
    b: 2,
    c: false,
  },
};

条件类型

  • extends
    • T extends U ? X : Y
  • Exclude<T, U> - 从类型 T 中排除掉那些可以赋值给类型 U 的类型
  • NonNullable<T> - 从类型 T 中移除 null 和 undefined
  • Extract<T, U> - 从类型 T 中提取所有可以赋值给类型 U 的类型
  • ReturnType<T> - 获取函数类型 T 的返回类型
ts 复制代码
type IsString<T> = T extends string ? "Yes" : "No";

type Result1 = IsString<string>;  // "Yes"
type Result2 = IsString<number>;  // "No"
ts 复制代码
type ExcludeExample = Exclude<"a" | "b" | "c", "a" | "b">;  // "c"
ts 复制代码
type NonNullableExample = NonNullable<string | null | undefined>;  // string
ts 复制代码
type ExtractExample = Extract<"a" | "b" | "c", "b" | "c" | "d">;  // "b" | "c"
ts 复制代码
type MyFunction = (x: number, y: number) => string;

type ReturnTypeExample = ReturnType<MyFunction>;  // string
相关推荐
用户938515635075 分钟前
Next.js 笔记系统(二):Redis 数据服务与侧边栏组件拆分实战
javascript·全栈
知识分享小能手2 小时前
线性代数学习教程,从入门到精通,向量组的线性相关性 — 完整知识点梳理(7)
学习·线性代数·机器学习
Shell运维手记2 小时前
Linux 常用基础命令学习笔记
linux·运维·笔记·学习·算法·github
动词ing3 小时前
【学习笔记】C语言(数组指针与指针数组+字符数组+函数+参数传递+字符串作为形参+递归函数+指针函数+回调函数+结构体嵌套+内存动态分配函数)
c语言·笔记·学习
Heo4 小时前
大厂前端调试不能只会debugger
前端·javascript·面试
想要成为糕糕手4 小时前
🚀 在浏览器里跑 DeepSeek-R1?WebGPU 端侧推理实战(六)—— 完结篇:消息渲染与流式收尾
react.js·typescript·llm
小O的算法实验室4 小时前
IEEE TII,学习为多目标深度学习生成偏好
人工智能·深度学习·学习
windliang5 小时前
Claude Code 源码分析(十二):错误处理与自动恢复:让 Agent 稳定运行
前端·javascript·面试
默_笙5 小时前
🛬 前端路由的"高级玩法":懒加载、404、鉴权路由,一个都不能少(下篇)
前端·javascript
sunly_5 小时前
TypeScript:3、类型声明与类型推断
javascript·ubuntu·typescript