Typescript 태그가 지정된 템플릿 문자열

템플릿 문자열을 함수로 사용하는 방법

기본 사항 : 템플릿 문자열

템플릿 리터럴이라고도하는 태그가있는 템플릿 문자열에 대해 이야기하기 전에 일반적인 템플릿 문자열에 대해 간단히 소개하겠습니다. 이것이 무엇인지 이미 알고 있다면 다음 장으로 건너 뛰어도됩니다.

템플릿 문자열은 Javascript 표현식을 포함 할 수있을뿐만 아니라 여러 줄에 걸쳐있는 특수한 유형의 문자열 기호입니다. 일반적인 문자열의 경우처럼 큰 따옴표 대신 백틱 문자를 사용합니다.

여러 줄에 걸친 문자 범위와 관련하여 공통 문자열에는 새 줄을 만들기 위해 문자 "n"과 함께 백 슬래시가 포함되어야합니다. 템플릿 문자열을 사용하면 간단히 새 줄 "인라인"을 만들 수 있습니다.

// A common string as reference.
const string = "I'm just a string";

// A template string. For Typescript,
// this value is a plain 'string'-type.
const templateString = `I'm just a string as well`;

문자열 내 표현식의 가용성도 빠르게 설명 할 수 있습니다. 문자열 기호를 허용하는 대신 템플릿 문자열은 임의의 표현식을 허용합니다. 다음 예는 내가 의미하는 바를 보여줍니다.

function greet(name: string) {
  // Here you see an expression
  // *embedded* inside a string.
  return `Hello, ${name}!`;
}

// "Hello, Tom!"
const greeting = greet("Tom");

// One more example, using
// Typescript's 'rest'-operator
// which allowes any number of values
// and provides them as an array,
// in our case of type 'string'.
function greetAll(...names: string[]) {
  return `Hi everybody: ${names.join(", ")}!`;
}

// "Hi everybody: Tom, Luke!"
const greetingForAll = greetAll("Tom", "Luke");

태그가 지정된 템플릿 문자열

이 기능 세트만으로도 이미 좋겠지 만 템플릿 문자열도 함수로 사용할 수 있습니다. 템플릿 문자열 앞에 키워드를 삽입하여 "태그"하므로 이름은 "태그 된 템플릿 문자열"입니다. 다음 예제를위한 시간입니다.

// All previous examples used 'untagged'
// string literals, which means they're 
// practially just a string.
//
// But let's see how we can convert them
// to an acutal function:
function merge(template: TemplateStringsArray, ...params: string[]){
  
  // This needs some explanation:
  //
  // 'template', our first param, contains
  // all strings *inbetween the paramters*,
  // you'll see in a minute what I mean by that.
  //
  // 'params' then is an array of strings
  // that were provided as paramteres to the
  // template string.
  
  // Let's ignore the result for now.
  return "";
}

const what = "test";

// Here's the tagged template string in action.
// The tag is the function name, and like a 
// function the tagged template string can be called.
//
// Let's destruct how this will look like
// in the function defined above.
//
// 'template' = ["Just a", ""];
// 'params'   = ["test"]
const result = merge`Just a ${what}`;

// As you can see, the function splits the string
// into the string-only parts and the expressions.

보시다시피 구문은 매우 흥미롭고 처음 작업 할 때 약간 이질적 일 수 있습니다. 태그가 지정된 템플릿 문자열을 구현해야하는 사용 사례는 많지 않지만 그럼에도 불구하고 우리는 그것을 가지고 놀 수 있습니다. 다음과 마지막 예에서는 몇 가지 사례 연구를 모았습니다. 보시다시피 태그가 지정된 템플릿 문자열은 자연스럽게 제네릭과 함께 사용할 수 있으며 특정 요구 사항을 구현하기위한 몇 가지 흥미로운 옵션을 열 수 있습니다.

// 
// Generic
//
// Tagged template literals can be generic, too.
function generic<T>(template: TemplateStringsArray, ...params: T[]){
    return template.join(",") + params.join(",")
}

// "A value: ,test"
console.log(generic<string>`A value: ${"test"}`);

//
// Generic (with super powers)
//
// You can specify each type and 
// also limit the number of params!
function coalesce<A, B, C>(template: TemplateStringsArray, ...params: [A, B, C]){
    return template.join(",") + params.join(",")
}

// ", - , - ,value,0,true" 
const res = coalesce<string, number, boolean>`${"value"} - ${0} - ${true}`;

//
// Different return type
//
// Also, tagged literal types don't 
// only have to return strings.
const preview = (template: TemplateStringsArray, ...params: number[]) 
  => (template2: TemplateStringsArray, ...params2: string[])
  => {
    return "what?";
}

// Note the two pairs of backticks
// after each other, we're just calling
// the returned tagged template string
// form our first one!
console.log(preview`${0}``${"a"}`);

Javascript와 Typescript의 기능 중 하나에 대한 다소 빠른 현장 학습을 즐기 셨기를 바랍니다. 템플릿 문자열은 코드베이스에서 일반적으로 사용되지만 태그가 지정된 템플릿 문자열은 그렇지 않을 수 있으므로 이러한 틈새 기능에 대해 자세히 알아 보는 것이 흥미 롭습니다.

제안

관련된

부록

언어