🍇

テンプレートリテラル (Template literals) メモ

に公開

バッククォート (`) で囲んだ文字列をテンプレートリテラルという。

`aaa bbb ccc` // バッククォート (`) で囲んでいる

タグ付きテンプレートmyTag'xxx'

myTag`This ${fruit} is ${color}.`;

上記の構文では、myTagという関数を呼び出している。中身は以下の通り。

const fruit = "apple";
const color = 'red';

function myTag(strings, fruitExp, colorExp) {
  console.log(`string[0] is ${strings[0]}`)
  const str0 = strings[0]; // "This "
  const str1 = strings[1]; // " is "
  const str2 = strings[2]; // "."
  return `${str0}${fruitExp}${str1}${colorExp}${str2}`;
}
const output = myTag`This ${fruit} is ${color}.`;
console.log(output); // "This apple is red."

記号やキーワードの呼び方や使い方を調べたいときはこのサイトが便利

索引:記号とキーワード | TypeScript入門『サバイバルTypeScript』

Discussion