Ts 类型 工具 方法

1. Exclude<T, U>:

Exclude 是一个内置的条件类型,用于从联合类型 T 中排除 U 中存在的类型。它通常用于类型过滤。

TypeScript 复制代码
{
  /**
   * 一般用于简单类型, 从联合类型中过滤某些类型
   */
  type A = string | number | boolean;
  type B = Exclude<A, string>; // number | boolean
  type C = Exclude<A, string | boolean>; // number
}

2. Omit<T, K>:

Omit 用于从类型 T 中排除某些键(K)。它主要用于对象类型的部分属性排除。

TypeScript 复制代码
{
  /**
   * type 类型 或 interface 类型的排除
   */
  type A = {
    a: string;
    c: number;
    d: boolean;
  };

  type B = Omit<A, 'a' | 'c'>;
}

3. NonNullable<T>:

NonNullable 是一个内置工具类型,用于从类型 T 中排除 null 和 undefined。

TypeScript 复制代码
{
  /**
   * NonNullable : 排除 null 和 undefined
   */
  type A = string | number | null | undefined;
  type B = NonNullable<A>; // string | number
}

4. Pick<T, K>:

Pick 是一个工具类型,它从类型 T 中提取一组属性 K。它主要用于对象类型的部分属性选择。

TypeScript 复制代码
{
  /**
   * Pick 从对象中提取某些属性
   */
  type A = {
    a: string;
    b: number;
    c: boolean;
    d: string | number;
  };
  /**
   * type B = {
   *  a: string;
   *  d: string | number;
   * }
   */
  type B = Pick<A, 'a' | 'd'>;
}

5. readonly 和 DeepReadonly:

• readonly 是一个 TypeScript 修饰符,用于将某个属性标记为只读,意味着该属性不能被修改。

• DeepReadonly 是自定义的类型,它会递归地将对象及其所有嵌套属性都变为只读。

TypeScript 复制代码
{
  /**
   * readonly 标记为只读
   * DeepReadonly 将所有属性都变为只读
   */
  type A = {
    readonly a: string;
    readonly b: number;
  };
  const a: A = {
    a: '1',
    b: 2
  };
  // a.a = '2'; // 无法为"a"赋值,因为它是只读属性。

  type C = {
    a: {
      b: string;
    };
  };
  type D = DeepReadonly<C>; // 将所有属性都变为只读
}

6.提取数组中 item 项的类型

TypeScript 复制代码
{
  /**
   * 提取数组中 item项 的类型
   */
  type A = string | number[];
  type B = A[number]; // string | number
}
相关推荐
烬羽1 天前
NestJS 依赖注入:Controller 里那个没有 new 的 service,到底从哪来的?
设计模式·typescript·nestjs
heyCHEEMS1 天前
切页回来组件消失了?一个浏览器渲染机制引起的容器高度坍塌 bug
前端·浏览器
iaku1 天前
Prompt 不是玄学:写给前端的 Prompt 工程指南
前端·人工智能
爱丶不疚1 天前
在 dsh 仓库里扒到的宝藏工作流:详解 .agents/notes 决策沉淀系统
前端·agent·vibecoding
喜欢睡觉1 天前
从"送花"讲懂 JavaScript:对象、数据类型与代理模式
前端
渣波1 天前
NestJS 企业级后端架构实战:从核心代码到工程化思维的深度重构
前端·typescript·nestjs
BreezeJiang1 天前
别再背工厂模式了:NestJS 第一行代码就是它的工业级落地
前端·javascript
光影少年1 天前
RN 常见性能问题:JS卡顿、UI卡顿、桥接通信耗时
前端·react native·react.js
liuxiaocheng1 天前
文本生成的进阶:generateText / streamText 里迟早会撞上的东西
前端·后端·ai编程
嘟嘟07171 天前
NestJS 入门:从 NestFactory 入口到 Module/Controller/Service 模块化结构一次讲清
typescript·node.js·nestjs