본문 바로가기
Web/JavaScript

[TypeScript] Template Literal Types

by llHoYall 2021. 3. 21.

Template Literal Types build on string literal types, and have the ability to expand into many strings via unions.

They have the same syntax as template literal strings in JavaScript, but are used in type positions. When used with concrete literal types, a template literal produces a new string literal type by concatenating the contents.

type TypeA = "AAA";
type TypeBC = "BBB" | "CCC";
type TypeDE = "DDD" | "EEE";

type TestType1 = `Test ${TypeA}`;
// Test AAA

type TestType2 = `${TypeBC | TypeDE}_id`;
// BBB_id | CCC_id | DDD_id | EEE_id

type TestType3 = `${TypeBC}_${TypeDE}`
// BBB_DDD | BBB_EEE | CCC_DDD | CCC_EEE

Intrinsic String Manipulation Types

To help with string manipulation, TypeScript includes a set of types which can be used in string manipulation.

Uppercase<StringType>

type Uppercase<S extends string> = intrinsic;

Converts each character in the string to the uppercase version.

Lowercase<StringType>

type Lowercase<S extends string> = intrinsic;

Converts each character in the string to the lowercase equivalent.

Capitalize<StringType>

type Capitalize<S extends string> = intrinsic;

Converts the first character in the string to an uppercase equivalent.

Uncapitalize<StringType>

type Uncapitalize<S extends string> = intrinsic;

Converts the first character in the string to a lowercase equivalent.

댓글