shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 508 forks source link

【Q693】在 ts 中如何实现 Partial #714

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

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

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

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",
});
shfshanyue commented 3 years ago
type Partial<T> = {
  [P in keyof T]?: T[P]
}