実務で学んだTypeScriptの使い方まとめ。

Extract<T, U>で特定の方を抽出する

ユニオン型TからUで指定した型だけを抽出した型を返すユーティリティ型

https://typescriptbook.jp/reference/type-reuse/utility-types/extract

// 野球場のユニオン型
type BaseballGroundType = "EhimeStadium" | "FukuokaStadium" | "TokushimaStadium" | "HyogoStadium";

// 四国の野球場のユニオン型
type ShikokuStadiumType = Extract<BaseballGroundType, "EhimeStadium" | "TokushimaStadium">

「as const」を使って配列からユニオン型を生成する

// 選手情報の配列
const players = [
	{ name: "John", position: "P" },
	{ name: "Peter", position: "1B" },
	{ name: "Beck", position: "2B" },
] as const

// 選手名のユニオン型を生成
type PlayerNameType = typeof players[number]["name"]

// 選手のポジションのユニオン型を生成
type PlayerPositionType = typeof players[number]["position"]
カテゴリー: JavaScript