テンプレート文字列とは
バッククオート`で囲った文字列のこと。変数展開が使える。
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)