// 公共接口
interface Info {
name:string,
age:number,
sex:string
}
1、keyof
与接口配合使用
// 1.1 基础用法:遍历属性
type Person = {
id: number;
name: string;
age: number;
};
type P1 = keyof Person; // 'id' | 'name' | 'age'
// 1.2 实际应用:获取属性值
type P2 = Person[keyof Person]; // number | string
// 1.3 约束范型参数的范围
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type P3 = MyPick<Person, "id" | "age">
与对象配合使用
const STATUS = {
CREATE: 'create',
EDIT: 'edit'
}
interface IProps {
title: string;
status: keyof typeof STATUS;
}
2、Readonly:将所有属性改为只读属性
// 原理
// type Readonly<T> = {
// readonly [P in keyof T]: T[P];
// }
const infoReadonly:Readonly<Info> = {
name: "sss",
age: 18,
sex: "男"
}
3、Pick:找到泛型 T 中的 K 属性
// 原理
// type Pick<T, K extends keyof T> = {
// [P in K]: T[P];
// }
const info3:Pick<Info, "name"> = {
name: "张三"
}
4、Omit:找到泛型 T 中除了 K 以外的属性
// 原理
const infoOmit:Omit<Info, "name"> = {
age: 16,
sex: "男"
}
5、Record:将 K 的每一个值都定义为 T 类型
// 原理
// type Record<K extends string, T> = {
// [P in K]: T;
// }
// 参数一:string、联合类型
// 参数二:对象、stirng、number
const infoRecord:Record<"yaoming", Info> = {
yaoming: {
name: "sss",
age: 18,
sex: "男"
}
}
6、Exclude:从 T 中剔除可以赋值给 U 的类型
// 从 a、b、c 中排除 a、b
// type T1 = "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">
7、Extract:类型交集 和 Exclude相反
// 求 a、b、c 和 a、b 的交集
// type T2 = "a" | "b"
type T2 = Extract<"a" | "b" | "c", "a" | "b">