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
}
相关推荐
coderYYY11 分钟前
element树结构el-tree,默认选中当前setCurrentKey无效
前端·javascript·vue.js
GISer_Jing42 分钟前
[总结篇]个人网站
前端·javascript
疯狂的沙粒1 小时前
在web-view 加载的本地及远程HTML中调用uniapp的API及网页和vue页面是如何通讯的?
前端·uni-app·html
小妖6661 小时前
html 滚动条滚动过快会留下边框线
前端·html
heroboyluck1 小时前
Svelte 核心语法详解:Vue/React 开发者如何快速上手?
前端·svelte
海的诗篇_1 小时前
前端开发面试题总结-JavaScript篇(二)
开发语言·前端·javascript·typescript
琹箐2 小时前
ant-design4.xx实现数字输入框; 某些输入法数字需要连续输入两次才显示
前端·javascript·anti-design-vue
程序员-小李2 小时前
VuePress完美整合Toast消息提示
前端·javascript·vue.js
Uyker2 小时前
从零开始制作小程序简单概述
前端·微信小程序·小程序
EndingCoder7 小时前
React从基础入门到高级实战:React 实战项目 - 项目三:实时聊天应用
前端·react.js·架构·前端框架