1
1

More than 1 year has passed since last update.

【TS】オブジェクトをマージする際の型定義はPartial<T>を使うと便利

Last updated at Posted at 2023-01-28

結論

オブジェクトをマージする際や上書きする際の型定義はPartial<T>を使うと便利です。

どんな時に使えるの?

たとえば、TSの公式ドキュメント(partialtype)が提供されているケースでは、updateTodo関数が、Todo型であるtodo1のオブジェクトに、更新対象のtodo2のプロパティで上書きする場合が挙げられています。

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",
});
/** output: {
 * title: "organize desk",
 * description: "throw out trash",
 * }
**/

さいごに

実際の開発現場では、JSスプレッド構文を利用したマージ処理のときに結構使えるケースが多い、という所感です。
Partial<T>の他にも、TSがいろんなユーティリティタイプを提供しています。
TSのutility-types ← 興味があったらぜひのぞいてみてくださいね~

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1