TS 原文是叫做 Utility Types,可以翻译成实用类型,玩转技巧的类型,暂定高级类型吧,感觉这些是玩转类型的灵魂方法。
TypeScript 提供一些全局通用方法,可以让你玩转类型转换,下面一起看看。
Partial<Type>
作用:将类型属性都设置为可选
代码语言:javascript复制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",
});
Required<Type>
作用:和Partial 相反,将类型属性都设置为必须
代码语言:javascript复制interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };
//Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
Readonly<Type>
作用:将类型属性设置成Readonly
代码语言:javascript复制interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
todo.title = "Hello";
//Cannot assign to 'title' because it is a read-only property.
这个技巧在运行时赋值表达式十分有用,例如冷冻一个对象( frozen object)):
Object.freeze
代码语言:javascript复制function freeze<Type>(obj: Type): Readonly<Type>;
Record<Keys,Type>
作用: Record<K,T>构造具有给定类型T的一组属性K的类型。在将一个类型的属性映射到另一个类型的属性时,Record非常方便。
源码:
代码语言:javascript复制/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
例子:
代码语言:javascript复制interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
更多实战案例:https://zhuanlan.zhihu.com/p/356662885
Pick<Type, Keys>
作用: 构造一个类型从另一个类型的属性中挑选出几个
源码:
代码语言:javascript复制/**
* From T, pick a set of properties whose keys are in the union K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
例子:
代码语言:javascript复制interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
Exclude<Type, ExcludedUnion>
作用:构造一个类型从另一个类型中剔除部分属性key
Omit<Type, Keys>
作用:构造一个类型从另一个类型中剔除部分属性key
源码:
代码语言:javascript复制/**
* Construct a type with the properties of T except for those in type K.
*/
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
例子:
代码语言:javascript复制interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
todo;
const todo: TodoPreview
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
todoInfo;