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
相关推荐
fangzhanpeng16844 分钟前
(前端)2.js变量作用域样例
开发语言·前端·javascript
码艺-Alimjan3 小时前
Vue项目源码备份最佳实践:无视node_modules,打包体积仅2MB
前端·javascript·vue.js
xixiaoyunya5 小时前
JavaScript 异步编程全解析:从回调地狱到 async/await 的演进之路
开发语言·javascript·ecmascript
张元清5 小时前
React useScrollLock Hook:为弹窗锁住页面滚动 (2026)
javascript·react.js
Sayai5 小时前
【无标题】ECharts 实现日志量异常检测:基线 ±Kσ 基带 + 灵敏度切换(Vue2 实战)
前端·javascript·echarts
zjnlswd5 小时前
C#学习笔记4
笔记·学习·c#
minglie15 小时前
在linux环境烧录esp8266
学习
默_笙6 小时前
💌 为了把"主题色"传给孙子组件,我翻了五层楼——直到遇见了 useContext
前端·javascript
xqqxqxxq6 小时前
AI Agent学习:MCP与工具生态:工具选择的挑战(李博杰《深入理解 AI Agent》4.3观后总结)
人工智能·学习
小KK_6 小时前
JS 事件循环从小白视角入门:宏任务、微任务与 async/await 一网打尽
前端·javascript