🤠

TypeScriptでリテラル型から型を抽出するExtract

2022/05/06に公開

TypeScriptのExtract(抽出)だけでも知っておくいいかもというお話.

TypeScriptを使っていてこんな型を使うことも少なくないはず

type Action =
  | {
      type: 'text';
      id: string;
      content: string;
    }
  | {
      type: 'amount';
      id: string;
      content: number;
    }
  | {
      type: 'route';
      id: string;
      path: string;
      blank: boolean;
    };

オブジェクトのリテラル型というやつだ.

こいつのここの部分だけ抽出したいとする.

{
  type: 'route';
  id: string;
  path: string;
  blank: boolean;
};

これでOK

const routeAction123: Extract<Action, { type: "route" }> = {
  type: "route",
  id: "foooooooooo",
  path: "/happy",
  blank: true
};

活用事例

https://zenn.dev/nbr41to/articles/2e51631bc47f6d

Discussion