• 主页
  • 归档
  • 分类
  • 照片墙
所有文章 友情链接 关于我

  • 主页
  • 归档
  • 分类
  • 照片墙
  1. 1. Partial<Type>
  2. 2. Readonly<Type>
  3. 3. Record<Keys, Type>
  4. 4. Pick<Type, Keys>
  5. 5. Omit<Type, Keys>

TypeScript实用工具类型

2021-05-11 15:22:09
总字数 368
预计阅读时间 1 分钟

TypeScript当中有一些内置的类型,适用于编译过程

Partial<Type>

将Type的所有属性都设置为可选的,表示输入类型的所有子类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface Person {
name: string
code: number
}

function show1(person: Partial<Person>) {
console.log(person)
}

function show2(person: Person) {
console.log(person)
}

show1({name: 'sookie'})
show2({name: 'sookie'}) // ERROR: Argument of type '{ name: string; }' is not assignable to parameter of type 'Person'.

Readonly<Type>

将Type的所有属性都设置为readonly

1
2
3
4
5
6
7
8
9
10
11
interface Person {
name: string
code: number
}

const person: Readonly<Person> = {
name: 'sookie',
code: 1
}

person.code = 2 // ERROR: Cannot assign to 'code' because it is a read-only property.

Record<Keys, Type>

用来将某个类型的属性映射到另一个类型上

1
2
3
4
5
6
7
8
9
10
11
interface PageInfo {
title: string
}
// 必须满足 string | number | symbol
type Page = 'home' | 'about' | 'contact'

const item: Record<Page, PageInfo> = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { title: 'home' },
}

Pick<Type, Keys>

从类型Type中挑选部分属性Keys来构造类型

1
2
3
4
5
6
7
8
9
10
11
12
interface Person {
name: string
age: number
remark: string
}
// 这里的第二个泛型值必须是属于 keyof Person
type PersonPick = Pick<Person, 'name' | 'age'>

const p: PersonPick = {
name: 'sookie',
age: 10
}

Omit<Type, Keys>

与Pick用法类似,作用是相反的,用于从中剔除若干个key

1
2
3
4
5
6
7
8
9
10
11
interface Person {
name: string
age: number
remark: string
}
type PersonOmit = Omit<Person, 'remark' >

const p: PersonOmit = {
name: 'sookie',
age: 10
}
  • TypeScript
  • 前端杂烩

扫一扫,分享到微信

Vue3新特性总结
TensorFlow.js初见(2) 
© 2024 夏夜梦星辰
鲁ICP备19028444号
Power By Hexo
  • 所有文章
  • 友情链接
  • 关于我
{{searchItem.query}}
标签: 分类:
  • maven
  • 持续集成
  • JMS
  • 线程
  • JavaScript
  • ECMAScript6
  • 单元测试
  • Promise
  • Web Worker
  • 函数
  • prototype
  • 模块化
  • 正则表达式
  • 数据库
  • MongoDB
  • 索引
  • 集群
  • 全文检索
  • flutter
  • dart
  • git
  • 版本控制
  • linux
  • shell
  • docker
  • nginx
  • jenkins
  • opencv
  • vim
  • react
  • react native
  • 前端
  • css
  • HTML5
  • Hexo
  • sass
  • Three.js
  • TypeScript
  • Vue
  • 组件化
  • base64
  • webpack
  • nodejs
  • gulp
  • TensorFlow
  • 机器学习
  • 算法
  • 动态规划
  • 数据结构
  • Java
  • JavaScript
  • MongoDB
  • flutter
  • Git
  • linux
  • react
  • 前端杂烩
  • 男生女生
  • 算法
  • 十年饮冰,难凉热血
  • †少女癌†
  • 猫与向日葵
  • coderfun
  • JENKINS
  • API管理后台
愿你最终能接纳每一面每一种的自己
独自活着便是团圆