当前位置: 首页 > article >正文

ts 中 Omit 作用

在 TypeScript 中,`Omit<T, K>` 是一个实用的类型操作工具,用于从一个类型中排除特定的属性,创建一个新的类型。

一、基本用法

1. 语法结构

`Omit<T, K>`接受两个类型参数,`T`表示要操作的原始类型,`K`表示要排除的属性名称的联合类型。

interface Person {

  name: string;

  age: number;

  gender: string;

}

type PersonWithoutAge = Omit<Person, "age">;

2. 排除多个属性

`K`可以是多个属性名称的联合类型,用于同时排除多个属性。

type PersonWithoutAgeAndGender = Omit<Person, "age" | "gender">;

二、实际应用场景

1. 函数参数类型定义

在定义函数的参数类型时,可以使用`Omit`来排除一些不相关的属性,使参数类型更加简洁和明确。

function updatePerson(person: Omit<Person, "gender">) {

  // 更新人员信息,不包括性别属性

}

2. 接口扩展

在接口扩展中,可以使用`Omit`来排除一些不需要的属性,然后再添加新的属性。

interface Employee extends Omit<Person, "gender"> {

  employeeId: number;

  department: string;

}


http://www.kler.cn/news/355512.html

相关文章:

  • JavaScript 第17章:性能优化
  • Chapter09
  • perl替换文件中的特定内容
  • 海南聚广众达电子商务咨询有限公司靠谱吗怎么样?
  • Uptime Kuma: 全面的开源网站监控解决方案
  • 青少年编程能力等级测评CPA C++(二级)试卷(2)
  • JavaScript的第三天
  • VSCode C/C++跳转到定义、自动补全、悬停提示突然失效
  • Rocky Linux 9安装Asterisk 20和freepbx 17脚本——筑梦之路
  • Rust各个方面完胜C++吗?
  • Threejs 实现3D 地图(01)创建基本场景
  • Parameter-Efficient Fine-Tuning for Large Models: A Comprehensive Survey阅读笔记
  • LeetCode1658.将x减到0的最小操作数
  • PHP爬虫API:获取商品详情的新利器
  • uniapp uni.uploadFile errMsg: “uploadFile:fail
  • PTA L1系列题解(C语言)(L1_073 -- L1_080)
  • php常用设计模式之单例模式
  • HikariPool连接池报错(Possibly consider using a shorter maxLifetime value)
  • 健康推荐新动力:SpringBoot智能系统
  • PostgreSQL与MySQL在语法上的区别