這是我參與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"
複製代碼