// 联合类型
let connect: string | number;
connect = "Tom";
connect = "13500000000";
// keyof 提取一个类型的属性名 作为联合类型
interface PersonModal {
name: string;
age: number;
hobby?: Array<string>;
}
type PersonKeys = keyof PersonModal;
const p1: PersonKeys = "name";
// Record 属性映射 <键类型,值类型>
type Person = Record<string, PersonModal>;
const persons: Person = {
p1: {
name: "Tom",
age: 18,
},
};
/** Record原理
type Record<K extends string | number | symbol, T> = {
[P in K]: T
}
*/
// Partial 部分的
const p2: Partial<PersonModal> = {
name: "Sam",
};
/** Partial原理
type Partial<T> = {
[P in keyof T]?: T[P]
}
*/
// Required 必须
type RequiredPerson = Required<PersonModal>;
const p3: RequiredPerson = {
name: "Tom",
age: 18,
hobby: ["football"],
};
// Pick 摘取
type PickPerson = Pick<PersonModal, "name" | "age">;
const p4: PickPerson = {
name: "Sam",
age: 16,
};
p4.age = 18;
// Readonly 只读
type ReadonlyPerson = Readonly<PersonModal>;
const p5: ReadonlyPerson = {
name: "Sam",
age: 16,
};
// p5.age = 18; // error
// Exclude 排除
type PersonTypes = "name" | "age";
type ExcludePerson = Exclude<PersonTypes, "name">;
const p6: ExcludePerson = "age";
// Omit 忽略
type OmitPerson = Omit<PersonModal, "name">;
const p7: OmitPerson = {
age: 20,
};