typescript进阶语法

typescript进阶语法

interface 接口定义

c 复制代码
interface userType {
	name:string,
	age:number,
	sex?:string
}

type接口定义

c 复制代码
type userType= {
	name:string,
	age:number,
	sex?:string
}
type userType ='username'  # 固定值写法
let user:userType = 'age'  # 报错 只能等于username

pick摘取部分类型

c 复制代码
type userType= {
	name:string,
	age:number,
	sex?:string
}
type myType=Pick<userType,'name'|'age'>
let my:myTyp={
	name:'张三',
	age:18
}

omit 剔除属性

c 复制代码
type userType= {
	name:string,
	age:number,
	sex:string
}
type myType=Pink<userType,'name'|'age'>
let my:myTyp={
	sex:'男'  # 加上其他属性就会报错,因为属性被剔除
}

Exclude 排除

c 复制代码
type a = 'a'|'b'|'c'
type b = 'b'|'c'
type Atype=Exclude<a,b> # a是否继承b 是 nerve 否 a,简单说a的类型b中是否有,有的话就是nerve空,否则就是a类型 相当于剔除
let data:Atype='a'

Extract 选择

c 复制代码
type a = 'a'|'b'|'c'
type b = 'b'|'c'
type Atype=Exclude<a,b> # 取a跟b的交集
let data:Atype='b'
let data2:Atype='c'

总结:当我们知道一组类型中需要剔除哪些属性时,就用Pink跟omit,当我们已知两组类型,但又不知道剔除哪些类型的时候就用Extract ,Exclude

Partial

将所有的属性变为可选属性

相关推荐
袋鱼不重1 小时前
Typescript 核心概念
前端·typescript
刮涂层_赢大奖2 小时前
我把 AI 编程 Agent 变成了宝可梦,让它们在像素风办公室里跑来跑去
前端·typescript·claude
时光不负努力1 天前
编程常用模式集合
前端·javascript·typescript
时光不负努力1 天前
ts+vue3开发规范
vue.js·typescript
时光不负努力1 天前
typescript常用的dom 元素类型
前端·typescript
时光不负努力1 天前
TS 常用工具类型
前端·javascript·typescript
Wect2 天前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
mCell2 天前
从零构建一个 Mini Claude Code:面向初学者的 Agent 开发实战指南
typescript·agent·claude
敲敲敲敲暴你脑袋2 天前
写个添加注释的vscode插件
javascript·typescript·visual studio code
Wect2 天前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript