Open1

TypeScript + Associated Valued Enum

みつよしみつよし
// 定義
interface ScreenshotButtonNone { kind: "none" }
interface ScreenshotButtonDefault { kind: "default" }
interface ScreenshotButtonCustom { kind: "custom", button: ReactNode }
type ScreenshotButtonType = ScreenshotButtonNone | ScreenshotButtonDefault | ScreenshotButtonCustom

// 値の指定
const screenshotButtonType: ScreenshotButtonCustom = {
  kind: "custom", // ScreenshotButtonCustomで定めた文字列と異なる値を入力するとコンパイラが検知してくれる
  button: ..., // associated valueを設定
}

// 値の読み出し
switch (screenshotButtonType.kind) {
case "none":
  ...
case "default":
  // screenshotButtonType.buttonなど別caseのassociated valueにアクセスしようとするとコンパイラが検知してくれる
case "custom":
  // screenshotButtonType.buttonからassociated valueにアクセス
}