🤠
TypeScriptでリテラル型から型を抽出するExtract
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
};
活用事例
Discussion