这是我参与8月更文挑战的第6天,活动详情查看:8月更文挑战html
Partial<Type>
:将类型的属性「变成可选」#源码:
type Partial<T> = {
[P in keyof T]?: T[P];
};
复制代码
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;
}
复制代码
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 }; //报错
复制代码
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"; // 这里只读属性,就报错了
复制代码
源码:
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
}
复制代码
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;
复制代码
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;
}
复制代码
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; }
复制代码
Exclude<Type, ExcludedUnion>
: 去除Type中包含ExcludedUnion的属性type T0 = Exclude<"a" | "b" | "c", "a">; // 去除Type中包含 "a" 的属性
type T0 = "b" | "c"
复制代码
Extract<Type, Union>
:取Type
和Union
都存在的属性type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T0 = "a"
复制代码