Template Literal Typesを使いこなす
2024-07-23

Template Literal Typesを使いこなす

#typescript

Template Literal Typesとは

JavaScriptには文字列リテラルに変数を埋め込むことが可能な、テンプレートリテラルという機能があります。

const port = 3000
console.log(`Listening on port ${port}`)
// Listening on port 3000

このテンプレートリテラルをTypeScriptに拡張したものがTemplate Literal Typesです。
これにより、文字列ベースの型定義をよりリッチ行うことができます。

使い方

APIエンドポイントに型定義をする場合の実装例です。

type Endpoint = `https://${string}/${string}`
const endpoint1: Endpoint = 'https://example1.com/users' // OK
const endpoint2: Endpoint = 'http://example2.com/posts' // NG
// Type '"http://example2.com/posts"' is not assignable to type '`https://${string}/${string}`'.

http通信をしようとしたら、TypeScriptエラーになりました。🎉
シンプルな運用でも十分に便利であることがわかったと思います。

実践編

CSS in JSを安全に型運用する場合の実装例です。

type Position = 'Top' | 'Right' | 'Bottom' | 'Left'
type CSSProperty = `margin${Position}`
type CSSValue = `${number}px`
type Margin = Partial<Record<CSSProperty, CSSValue>>
 
const marginA: Margin = {
  marginTop: '10px',
  marginRight: '15px',
} // OK
 
const marginB: Margin = {
  margintop: '10px',
  // Object literal may only specify known properties, ... Did you mean to write 'marginTop'?
  marginRight: '15',
  // Type '"15"' is not assignable to type '`${number}px`'.
} // NG

キー名の型定義の一部(プレフィックスのmargin)を共通化することで、直感的に理解しやすい定義になりました。
また、pxをサフィックスに付与することも強制できています。

まとめ

Template Literal Typesは文字列型を柔軟かつ、厳密に定義に扱えるようにしてくれることをお伝えしました。
他にもTypeScriptの記事を投稿していくのでお楽しみに!
Happy Coding !!👍

© 2024 Both Arms. All Rights Reserved.