템플릿 리터럴은 JavaScript 및 TypeScript에서 문자열을 생성하기 위한 문법적인 기능입니다. 템플릿 리터럴을 사용하면 문자열 안에 변수, 표현식, 줄바꿈 등을 쉽게 포함할 수 있습니다. 아래는 템플릿 리터럴의 몇 가지 예시입니다:
const name = 'John';
const age = 30;
const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message);
// 출력: My name is John and I'm 30 years old.
const a = 10;
const b = 5;
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result);
// 출력: The sum of 10 and 5 is 15.
const multiLine = `
This is
a multi-line
string.
`;
console.log(multiLine);
// 출력:
// This is
// a multi-line
// string.
function customTag(strings, ...values) {
console.log(strings);
console.log(values);
}
const item = 'apple';
const price = 2.5;
customTag`The price of ${item} is ${price} dollars.`;
// 출력:
// [ 'The price of ', ' is ', ' dollars.' ]
// [ 'apple', 2.5 ]
위의 예시에서 ` 문자로 문자열을 감싸고, ${} 안에 변수 또는 표현식을 넣어서 템플릿 리터럴을 작성할 수 있습니다. 이렇게 작성된 템플릿 리터럴은 해당 변수 또는 표현식의 값으로 대체됩니다. 또한, 다중 줄 문자열을 쉽게 작성하거나 태그드 템플릿 리터럴을 사용하여 특별한 처리를 할 수도 있습니다.