Required<Type>
构造一种类型,它是由设置为required的Type的所有属性组成。相反由部分属性组成则使用Partial
interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };
在'{ a: number; }' 中属性 'b' 可以缺失,但是在 'Required<Props>'中属性 'b'为必须属性;
Partial<Type>
构造一种类型 type,它是由Type的所有属性作为可选项。它将返回所给的Type的所有属性的子集的类型;
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
const todo1 = {
title: "organize desk",
description: "clear clutter",
};
const todo2 = updateTodo(todo1, {
description: "throw out trash",
});
Readonly<Type>
构造一种类型 type,它的所有 properies 属性都被设置为只读属性,意味着该类型的所有属性不能被赋值。
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
todo.title = "Hello";
不能给title属性赋值,因为他是只读属性。
Record<Keys,Type>
构造一种对象类型 object type ,它的属性 key 值为keys,对应的 value 值为Type,它可以用于将一个类型的属性映射到另外一个类型;
interface PageInfo {
title: string;
}
type Page = "home" | "about" | "contact";
const nav: Record<Page, PageInfo> = {
about: { title: "about" },
contact: { title: "contact" },
home: { title: "home" },
};
todo;
// ^ = const todo: TodoPreview
Pick<Type, Keys>
构造一种类型 type,通过选择Type中的一组属性Keys
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
// ^ = const todo: TodoPreview
Omit<Type, Keys>
构造一种类型 type,通过选择Type中的所有属性并移除Keys
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
// ^ = const todo: TodoPreview
Exclude<Type, ExcludedUnion>
构造一种类型 type,通过排除赋值给ExcludedUnion的所有Type类型的联合成员;
type T0 = Exclude<"a" | "b" | "c", "a">;
// ^ = type T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
// ^ = type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>;
// ^ = type T2 = string | number
Extract<Type, Union>
构造一种类型 type,通过提取赋值给Union的所有Type类型的联合成员;
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// ^ = type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;
// ^ = type T1 = () => void