Script - Template Literal Types

Template Literal Types

template literal types 는 string literal types를 바틍으로 만들어지고 많은 string 타입들을 유니온으로 확장할 수 있다.

type World = "world";
type GREETING = `HELLO ${World}`

console.log(typeof Greeting) //"hello world"

자바스크립트의 template literal string 과 똑같지만 type 선언에 쓰인다.

유니온도 사용 가능하다.

type EmailLocaleIDs = "welcome_email" | "email_heading";
type FooterLocaleIDs = "footer_title" | "footer_sendoff";

type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;

console.log(typeof AllLocaleIDs) // "welcome_email_id" | "email_heading_id" | "footer_title_id" | "footer_sendoff_id"

또한, 여러개 사용도 가능하다

type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
type Lang = "en" | "ja" | "pt";
 
type LocaleMessageIDs = `${Lang}_${AllLocaleIDs}`;
console.log(typeof LocaleMessageIDs) // "en_welcome_email_id" | "en_email_heading_id" | "en_footer_title_id" | "en_footer_sendoff_id" | "ja_welcome_email_id" | "ja_email_heading_id" | "ja_footer_title_id" | "ja_footer_sendoff_id" | "pt_welcome_email_id" | "pt_email_heading_id" | "pt_footer_title_id" | "pt_footer_sendoff_id"

Instrinsic String Manipulation Types

문자열 조작을 위해서 타입스크립트는 여러가지를 제공한다

Uppercase

type Greeting = "hello, world";
type ShoutyGreeting = Uppercase<Greeting>;

console.log(typeof ShoutyGreeting); // "HELLO, WORLD"

type ASCIICacheKey<Str extends string> = `ID-${Uppercase<STR>}`;
type MainID = ASCCICacheKey<"my_app">;

console.log(typeof MainID); // "ID-MY_APP"

Lowercase

type Greeting = "HELLO, WORLD";
type QuietGreeting = Lowercase<Greeting>;

console.log(typeof QuietGreeting); // "hello, world"

type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`;
type MainID = ASCIICacheKey<"MY_APP">;

console.log(typeof MainID); // id-my_app

Capitalize

type LowercaseGreeting = "hello, world";
type Greeting = Capitalize<LowercaseGreeting>;

console.log(typeof Greetin); // "Hello, world";

Uncapitalize

type UppercaseGreeting = "HELLO WORLD";
type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>;

console.log(typeof UncomfortableGreeting) // "hELLO WORLD"

좋은 웹페이지 즐겨찾기