LoginSignup
4

More than 3 years have passed since last update.

TypeScript: テンプレート文字列のタグ関数の作り方

Last updated at Posted at 2020-05-22

テンプレート文字列とは

バッククオート`で囲った文字列のこと。変数展開が使える。

const str = `foo bar`
const str2 = `hoge ${str}`
//=> "hoge foo bar"

タグ関数とは

テンプレート文字列の前に書くことで、文字列を処理できる関数。この関数は受け取った文字列を処理して、文字列を返してもいいし、受け取った文字列を処理して、何らかのオブジェクトを返したりしてもいい。

const str = tag`foo baar`
         // ^^^ ここで使える関数

タグ関数の作り方

受け取った文字列をそのまま返す関数の実装例です:

const tag = (
  template: TemplateStringsArray,
  ...expressions: ReadonlyArray<any>
) => template.reduce((a, b, idx) => a + b + `${expressions[idx] ?? ''}`, '')
console.log(tag`hello world ${new Date()}`)
//=> hello world Fri May 22 2020 20:01:16 GMT+0900 (Japan Standard Time)

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
4