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
}
相关推荐
Geek-Chow8 分钟前
微服务认证与授权:01 — 概念
java·前端·数据库
狂炫冰美式28 分钟前
凌晨睡不着,我给台风巴威写了个追踪网站
前端·后端·github
雪隐1 小时前
用Flutter做背单词APP-01服务器?不存在的,我家里就有
前端·人工智能·后端
用户2204603958682 小时前
ES模块和commonJS两种标准下中实现__dirname?一篇文章教你理清楚
前端
犹豫的大炮2 小时前
jQuery最核心的基础设施之一——数据缓存模块进化史
前端·缓存·jquery
小碗细面2 小时前
从 PRD 到上线:SpecKit 如何让 AI 真正参与前端交付
前端·ai编程·claude
WL学习笔记2 小时前
链式队列(数据结构)
前端·数据结构·jquery
我是大卫2 小时前
React源码解析-第三部分:协调与提交
前端·react.js·源码
都想学2 小时前
我把 12 个在线工具关掉了,换成了一个 Chrome 扩展
前端·chrome
xiaogai_gai2 小时前
钉钉数据集成到金蝶云星空案例分享:传给钉钉后,回传金蝶字段
java·前端·钉钉