手打基础丸 🧆 => 精选基础知识,经过多道工序精心制作而成,口感鲜嫩多汁。一口咬下,香气四溢,加上传统前端风味,令人回味无穷...... 助力食用者厚积薄发,夯实根基进阶上层。
TS的索引访问类(查找类型)?
用于获取对象属性类型的一种方式,允许在已知属性名的前提下从类型中取出这个属性的类型。
typescript
interface f{
x:string,
y:number,
}
type newType = f['x'] // newType为string类型
TS中的条件类型?
类似与三元运算符,可以根据条件来确认类型
lua
T extends U ? string : int // true为string,false为int
TS中的映射类型?
可以用来使用已有类型生成新的类型,相当于可以进行一个批量操作
typescript
// 使用person生成映射类型,包含person的所有配置
type Partial<T> = {
[P in keyof T] ?: T[P]
}
type ReadonlyPartial<T> = {
[P in keyof T] : Readonly<T[P]>
}
interface f{
x:string,
y:number,
}
// 映射过来的type会将所有f中的属性变为可选属性
type Partialf= Partial<f>
// 映射过来的type会将person中所有属性变为只读
type ReadonlyPartialf =ReadonlyPartial<f>
const p: Partialf = {x : 'myname'}
TS中的keyof关键字?
用来获取某个对象类型的所有键并生成一个联合类型
ini
type keys = keyof f // "x" | "y"
TS中的typeof关键字?
用来获取变量或表达式的类型
typescript
let num = 10
console.log(typeof num) // "number"
// 可以和keyof联合使用
const colors = {
red: "red",
green:"green"
}
type ColorKeys = keyof typeof colors // 类型为"red"| "green"
let color :Colorkeys = "blue"// 非法赋值
let color :Colorkeys = "red"// 合法赋值