2024-07-23
Template Literal Typesを使いこなす
Template Literal Typesとは
JavaScriptには文字列リテラルに変数を埋め込むことが可能な、テンプレートリテラルという機能があります。
このテンプレートリテラルをTypeScriptに拡張したものがTemplate Literal Typesです。
これにより、文字列ベースの型定義をよりリッチ行うことができます。
使い方
APIエンドポイントに型定義をする場合の実装例です。
http通信をしようとしたら、TypeScriptエラーになりました。🎉
シンプルな運用でも十分に便利であることがわかったと思います。
実践編
CSS in JSを安全に型運用する場合の実装例です。
キー名の型定義の一部(プレフィックスのmargin
)を共通化することで、直感的に理解しやすい定義になりました。
また、px
をサフィックスに付与することも強制できています。
まとめ
Template Literal Typesは文字列型を柔軟かつ、厳密に定義に扱えるようにしてくれることをお伝えしました。
他にもTypeScriptの記事を投稿していくのでお楽しみに!
Happy Coding !!👍
© 2024 Both Arms. All Rights Reserved.