路漫漫其修远兮,吾将上下而求索。
操作符
keyof
keyof 可以获取一个类型所有键值,返回一个联合类型。
type Person = {
name:string;
age:number;
}
type PersonKey = keyof Person; // 'name'|'age'
typeof
typeof 可以获取一个对象/实例的类型。
const person = {
name:'xiaobai',
age:3
}
const p1:typeof person = {
name:'xiaohong',
age:2
}
// typeof person 输出 {name:string, age:number}
in 操作符
遍历枚举的类型, 可以和keyof配合使用,作类型转换等。
type Person = {
name:string;
age:number;
}
type PersonToString<T> = {
[k in keyof T]:string
}
const p1:PersonToString<Person> = {
name:'xiaobai',
age:"10"
}
// {name:string, age:string}
使用例子
实现 Partial
Partial<Type>
是一个ts内置工具类型,用于将传入的类型所有属性设置为可选的。
type User = {
id:number,
phone:number,
pwd:string,
name:string
}
const u1:Partial<User> = {
id:1,
name:'小白'
}
// 自己实现
type MyPartial<T> = {
[k in keyof T]?: T[k]
}
const u2:MyPartial<User> = {
id:2,
name:'小红'
}
实现 Readonly
Readonly<Type>
工具类型可以将传入的类型中所有属性转化为只读。
type User = {
id:number,
name:string
}
// 自己实现
type MyReadonly<T> = {
readonly [k in keyof T]: T[k]
}
const u1:MyReadonly<User> = {
id:3,
name:'小黄'
}
u1.name = '小黑'
//Cannot assign to 'name' because it is a read-only property.
实现 Record
Record<Keys, Type>
工具类型可以将某个类型的属性映射到另一个类型上,其构造的类型属性名的类型为K,属性值的类型为T
type Page = 'home' | 'about' | 'contact';
interface PageInfo {
title: string;
}
const x1: Record<Page, PageInfo> = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { title: 'home' },
};
// 自己实现
type MyRecord<Keys extends keyof any, Type> = {
[k in Keys]: Type
}
const x2: MyRecord<Page, PageInfo> = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { title: 'home' },
};