一、定义
可以将一个旧类型转换为新类型
interface myType1 {
name:string,
age:number
}
type cutType<T> = {
// [P in keyof T] 遍历出该类型中所有的属性
-readonly [P in keyof T] -?: T[P]
}
// + - 添加/删除 可读或者可选属性
//
type typeTest = cutType<myType1>
type typeTest1 = Readonly<myType1> // 全为只读属性
type typeTest2 = Partial<myType1> // 全为可选属性
type typeTest3 = Partial<Readonly<myType1>> // 全为只读可选属性
二、PIck和Record类型
pick类型:复制类型时,可以选择需要复制的属性进行复制。
interface myType3 {
name:string,
age:number
}
type t1 = Pick<myType3, 'name'>
record类型:复制类型时,可以选择需要复制的属性进行复制。
type t1 = Pick<myType3, 'name'>
type Animal = 'person' | 'dog' | 'cat'
type t2 = Record<Animal, myType3 >
let res: t2 = {
person :{
name:'string',
age:33
},
dog :{
name:'string',
age:33
},
cat :{
name:'string',
age:33
}
}
三、类型推断
interface test6 {
name:string,
age:number
}
type changeType<T> = {
readonly [P in keyof T]:T[P]
}
type test7 = changeType<test6>
type changeType1<T> = {
+readonly [P in keyof T]:T[P]
}
type test8 = changeType<test6>
type UnchangeType1<T> = {
-readonly [P in keyof T]:T[P]
}
type test9 = UnchangeType1<test8>