1
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?

型の共通部分の抽出方法

以下のようなUserAdminの型の共通部分を取得する場合を考えます。
UserはemailでログインするがAdminはloginIdでログインするような仕様を想定しています。

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

type Admin = {
  id: number;
  name: string;
  loginId: string;
};

以下のような記述で共通部分だけ抽出した型を作ることができます。

type Common = Pick<User, keyof User & keyof Admin>;

上記の型は以下と同じ型になります。

type Common = {
  id: number;
  name: string;
};

説明

ここから先は気になる方だけ。
ワンライナーで書いていた型を一つずつ紐解くと以下のようになります。
Pick&(インターセクション型)の意味や使い方についてはサバイバルTypeScriptが参考になるかと思います。

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

type Admin = {
  id: number;
  name: string;
  loginId: string;
};

type KeyOfUser = keyof User;
// => "id" | "name" | "email";

type KeyOfAdmin = keyof Admin;
// => "id" | "name" | "loginId";

type CommonKey = KeyOfUser & KeyOfAdmin;
// => "id" | "name";

type Common = Pick<User, CommonKey>;
// => { id: number; name: string; }

1
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
1
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?