LoginSignup
6
6

More than 1 year has passed since last update.

StringをStringリテラルのユニオン型に安全に型変換する

Last updated at Posted at 2023-01-11

型をかっちり固めて開発をする際に、リテラルのユニオン型は欠かせません。
ただし、URL ParameterやAPI Responseなどの受け口では、詳細な型情報の無いstringを受け取ることはよくあります。
型をかっちり固めて開発際には、その受け口で詳細な型に変換し、内部の詳細なロジックの実装部分では詳細な型情報の元で考慮を減らして開発したいものです。

型キャストとして as がありますが、型情報の強制的な上書きであり、実際の値と型との乖離を生む危険性があります。
type guardを定義して、安全な型変換を実現します。

結論

以下の様に実装することによって、isSample関数は型に合致するかを表すbooleanを返しつつ、引数に与えたString型の変数(sample)にSampleの型情報を付与します。

const samples = [
  'valueA',
  'valueB',
] as const
type Sample = typeof samples[number]

export const isSample = (
  sample: string
): sample is Sample => {
  return samples.some((v) => v === sample)
}

isSample関数は、以下のように使用できます。
想定外の文字列が与えられた場合は適切にハンドリングしつつ、想定どおりである場合には型情報が与えられた変数を利用できて便利です。

// type of sample: string
if (isSample(sample)) {
  // 文字列sampleがSample型に含まれている場合
  // type of sample: Sample
} else {
  // 文字列sampleがSample型に含まれていない場合
  // type of sample: string
}

type guard便利ですね。
type guardを利用すると、他の型同士の変換の実現にも応用できます!

6
6
1

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
6
6