Typescript 常用工具类型 Partial、Required、Readonly、Record、Pick、Omit

冯德宇
2023-12-01

目录

Partial

Required

Readonly

Record,>

Pick ,>

 Omit,>


Partial<Type>

将类型定义的所有属性都修改为可选。

type People = {
    name:stringage:number
}

type DemoPeople = Partial<People>;
// 相当于
type DemoPeople = {
    name?:string,
    age?:number
}

Required<Type>

所有属性为必需 和 Partial 刚好相反

interface Props {
  a?: number;
  b?: string;
}
 
const obj: Props = { a: 5 };
 
// 处理后属性为必须   这里只存在a 固 报错
const obj2: Required<Props> = { a: 5 };

Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'. 

Readonly<Type>

所有属性 只读  不能重新赋值

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. 

Record<Keys, Type>

以 typeof 格式快速创建一个类型,此类型包含一组指定的属性且都是必填。 

type Demo = Record<'a' | 'b', number>;

// 等同于
type Demo = {
	a: number;
	b: number;
}

Pick<Type, Keys> 

通过从 中选择一组属性Keys(字符串文字或字符串文字的并集)来构造类型Type,简单理解挑选或者提取

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

 Omit<Type, Keys>

删除某个key

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,
};
 类似资料: