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
相关推荐
晓得迷路了30 分钟前
栗子前端技术周刊第 94 期 - React Native 0.81、jQuery 4.0.0 RC1、Bun v1.2.20...
前端·javascript·react.js
江城开朗的豌豆31 分钟前
React Native 实战心得
javascript
rannn_11132 分钟前
【MySQL学习|黑马笔记|Day7】触发器和锁(全局锁、表级锁、行级锁、)
笔记·后端·学习·mysql
江城开朗的豌豆39 分钟前
React状态更新踩坑记:我是这样优雅修改参数的
前端·javascript·react.js
阿珊和她的猫1 小时前
autofit.js: 自动调整HTML元素大小的JavaScript库
开发语言·javascript·html
喜欢吃燃面1 小时前
C++算法竞赛:位运算
开发语言·c++·学习·算法
传奇开心果编程1 小时前
【传奇开心果系列】Flet框架实现的家庭记账本示例自定义模板
python·学习·ui·前端框架·自动化
阿珊和她的猫6 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
_Kayo_7 小时前
node.js 学习笔记3 HTTP
笔记·学习
CCCC131016311 小时前
嵌入式学习(day 28)线程
jvm·学习