这是我参与8月更文挑战的第6天,活动详情查看:8月更文挑战
1.Partial<Type>:将类型的属性「变成可选」
#源码:
type Partial<T> = {
[P in keyof T]?: T[P];
};
- 索引类型查询操作符: keyof
type Partial<T> = {
[P in keyof T]?: T[P];/ / 将每一对中的 key 变为可选,即添加 ?
}
- 使用
interface User {
name: string
age: number
department: string
}
type optional = Partial<User>
// optional的结果如下
type optional = {
name?: string | undefined;
age?: number | undefined;
department?: string | undefined;
}
2.Required<Type>:将类型的属性变成必选
源码:
type Required<T> = {
[P in keyof T]-?: T[P];
};
// 这里的 - 号是去除条件
- 使用
interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 }; //报错
3.Readonly<Type>:将类型T中的成员变为只读
源码:
type Readonly<T> = {
readonly [P in keyof T]: T[P]; // 就是在前面加了一个修饰符
};
- 使用
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
todo.title = "Hello"; // 这里只读属性,就报错了
4.Record:将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型
源码:
type Record<K extends string, T> = {
[P in K]: T;
}
- 使用
interface PageInfo {
title: string;
}
type Page = "home" | "about" | "contact";
const nav: Record<Page, PageInfo> = {
about: { title: "about" },
contact: { title: "contact" },
home: { title: "home" },
};
// Record 后面的泛型就是对象键和值的类型
# 有 ABC 三个属性,属性的值必须是数字
type keys = 'A' | 'B' | 'C'
const result: Record<keys, number> = {
A: 1,
B: 2,
C: 3
}
5.Pick<Type, Keys>:从一个复合类型中,取出几个想要的类型的组合
源码:
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
- 使用
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
6.Omit<Type, Keys>:从另一个对象类型中剔除某些属性,并创建一个新的对象类型
用Pick<T, Exclude<keyof T, K>>来表示
- 使用
type UserProps = {
name?:string;
age?:number;
sex?:string;
}
// 但是我不希望有sex这个属性我就可以这么写
type NewUserProps = Omit<UserProps,'sex'>
// 等价于
type NewUserProps = {
name?:string;
age?:number;
}
7.ReturnType 用来得到一个函数的返回值类型
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>;
type T0 = string
type T4 = ReturnType<typeof f1>;
type T4 = { a: number; b: string; }
8.Exclude<Type, ExcludedUnion>: 去除Type中包含ExcludedUnion的属性
type T0 = Exclude<"a" | "b" | "c", "a">; // 去除Type中包含 "a" 的属性
type T0 = "b" | "c"
9.Extract<Type, Union>:取Type和Union都存在的属性
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T0 = "a"