2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】Utility TypesのPartial型を理解する

Posted at

Utility Typesとは

Utility Types(ユーティリティ型)は、既存の型を元に新しい型を生成することができる型です。

Partial型とは

Partial型(パーシャル型)は、特定の型の全てのプロパティをオプショナル(任意)にすることができます。

Partial型の使用例

TypeScript(Partial型未使用の場合)
type UserProfile = {
  name: string;
  age: number;
  address: string;
};

このUserProfile型のプロパティは、現状全て必須です。
なので、UserProfile型のオブジェクトを作成する時には、nameageaddressの全てのプロパティを渡す必要があります。

そこで、もし一部のプロパティだけを扱いたい場合や、全てのプロパティが必ずしも存在しない場合に、Partial型を使用します。

TypeScript(Partial型使用の場合)
type PartialUserProfile = Partial<UserProfile>;

/*PartialUserProfileの型は以下のようになります
type PartialUserProfile = {
  name?: string;
  age?: number;
  address?: string;
*/
};

?記号は、そのプロパティが存在しても存在していなくても良いことを示しています。
つまり、各プロパティはオプショナル(任意)となります。

なので、Partial<UserProfile>を用いてオブジェクトを作成する際には、UserProfileの全てのプロパティが含まれていないくても問題ありません。

例えば以下のように、Partial<UserProfile>を用います。

TypeScript
const tanaka: PartialUserProfile = {
  name: 'Tanaka',
}

console.log(tanaka) //=>{ name: 'Tanaka' }

tanakaオブジェクトは、nameageaddressの全てのプロパティを含んでいないですが、Partial<UserProfile>によってオプショナルになっているため、問題ありません。

まとめ

Partial型(パーシャル型)を用いることで、特定の型の全てのプロパティをオプショナル(任意)にすることができました。

わかりやすい実例は今後追記していきたいと思います。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?