1
1

typescript の型を正規表現っぽく書く ( 型に型を埋め込む / Union型でOR表現する )

Last updated at Posted at 2024-01-31

コード例

以下のように、型指定の中に型を埋め込めるようだ

type SomeType1 = `${number}px`

文字列を OR でつないで正規表現チックにすることも出来る

type SomeType2 = `IT IS ${'YES' | 'NO'}`

正規表現そのものを書けるわけではないようだが、これを組み合わせると正規表現チックに書けそうだ

090で始まる電話番号とか

type PhoneNumber = `090${'-' | ''}${number}${'-' | ''}${number}`

全体をユニオン型でつないで OR 表現するとか

type RGB = `rgb(${number}, ${number}, ${number})`;
type RGBA = `rgba(${number}, ${number}, ${number}, ${number})`;
type HEX = `#${string}`;

type Color = RGB | RGBA | HEX;

動作確認例

type AnswerType = `IT IS ${'YES' | 'NO'}`

const answer1: AnswerType = 'IT IS YES' // これはOK
const answer2: AnswerType = 'IT IS WOW' // これは型エラー

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
1
0

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