极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# 在 ts 中如何实现 Partial

更多描述

实现 Partial,使得 Object 所有的属性变为可选属性。

PS: Partial 已经在 TS 中原生实现,见文档: https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype (opens new window)

type User = {
  id: number;
  age: number;
  name: string;
};

// Output:
// type PartialUser = {
//   id?: number | undefined;
//   age?: number | undefined;
//   name?: string | undefined;
// }
type PartialUser = Partial<User>;

以下是使用案例

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",
});

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 714 (opens new window)

type Partial<T> = {
  [P in keyof T]?: T[P];
};
Last Updated: 11/27/2021, 6:11:48 PM