🕳

何もしないタグ付きテンプレート

2022/02/03に公開

noop

noop は何もしない関数です。

const noop = () => {}

// TypeScript
const noop = (..._args: unknown[]) => {}

identity function (恒等関数)

渡された引数をそのまま返す関数です。

const identity = (v) => v
const identity = (...v) => v
// ts
const identity = (v: unknown) => v

何もしないタグ付きテンプレート

テンプレートリテラルは ${} で変数の埋め込みができます。

const name = 'world'
console.log(`hello ${name}`)
// hello world

タグ関数 は テンプレートリテラルを関数で解析できます。

const myTag = (a, b, c) => [a, b, c]

myTag`__${1}___${'str'}__`
// [ [ '__', '___', '__' ], 1, 'str' ]

テンプレートリテラル (テンプレート文字列) - JavaScript | MDN

styled-components などで使われています。

本題でただのテンプレートリテラルとして動くタグ関数(タグつきテンプレート関数)を作ってみる。

const identify = (strs: TemplateStringsArray, ...exps: any[]) =>
  strs.map((a, i) => a + String(exps[i] || '')).join('')
const name = 'world'
const suffix = '!!'

identify`hello ${name} ${suffix}.`
// 'hello world !!.'
;`hello ${name} ${suffix}.`
// 'hello world !!.'
GitHubで編集を提案

Discussion