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
相关推荐
炫饭第一名7 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
进击的尘埃9 小时前
Vue3 响应式原理:从 Proxy 到依赖收集,手撸一个迷你 reactivity
javascript
willow9 小时前
JavaScript数据类型整理1
javascript
LeeYaMaster9 小时前
20个例子掌握RxJS——第十一章实现 WebSocket 消息节流
javascript·angular.js
UIUV10 小时前
RAG技术学习笔记(含实操解析)
javascript·langchain·llm
颜酱12 小时前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
FansUnion12 小时前
我如何用 Next.js + Supabase + Cloudflare R2 搭建壁纸销售平台——月成本接近 $0
javascript
左夕13 小时前
分不清apply,bind,call?看这篇文章就够了
前端·javascript
滕青山14 小时前
文本行过滤/筛选 在线工具核心JS实现
前端·javascript·vue.js
时光不负努力14 小时前
编程常用模式集合
前端·javascript·typescript