Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Template Literal Types

TypeScript Template Literal Types

Template literal types build on string literal types and support generating new string types through interpolation.

This allows TypeScript to perform more precise type checking on strings, suitable for scenarios such as event names, paths, and class names.


How Template Literal Types Work Input Type type Event = "click" | "focus" type Method = "get" | "post" Template Template Literal Types type Name = `on${Capitalize}` type Path = `${Method}:/${string}` Output Type "onClick" "onFocus" "get:/..." Built-in Utility Types Uppercase "hello" → "HELLO" Lowercase "HELLO" → "hello" Capitalize "hello" → "Hello" Uncapitalize "Hello" → "hello"

Why Template Literal Types Are Needed

In development, we often need to handle formatted strings, such as event names (onClick), API paths (get:/users), and CSS class names (btn-primary-md).

Using the ordinary string type cannot precisely describe these formats, while template literal types let us precisely define the types of these strings.

This greatly enhances TypeScript's type safety and reduces runtime errors.

Concept explanation:Template literal types use backticks (`` ` ``) and ${} interpolation syntax to define string types, similar to JavaScript's template strings, but at the type level.


Basic Syntax

Template literal types use backticks and interpolation to define types.

Example

// Define a basic string literal type

type World

=

"world"

;

// Use template literal types

// Hello ${World} Equivalent to "Hello world"

type Greeting

=

`Hello $

{

World

}

`

;

// Only strings matching the type definition can be assigned

var

greeting

:

Greeting

=

"Hello world"

;

console.

log

(

"Greeting: "

greeting

)

;

Running result:

问候: Hello world

Explanation:Template literal types replace the interpolation positions with actual strings, generating new literal types.


Built-in Utility Types

TypeScript provides four built-in utility types for handling string case.

Example

// Uppercase: convert a string to uppercase

type UpperHello

=

Uppercase

<

"hello"

;

 

// "HELLO"

// Lowercase: convert a string to lowercase

type LowerHELLO

=

Lowercase

<

"HELLO"

;

 

// "hello"

// Capitalize: capitalize the first letter of a string

type CapitalizedHello

=

Capitalize

<

"hello"

;

 

// "Hello"

// Uncapitalize: lowercase the first letter of a string

type UncapitalizedHello

=

Uncapitalize

<

"Hello"

;

 

// "hello"

console.

log

(

"Uppercase: "

UpperHello

)

;

console.

log

(

"Lowercase: "

LowerHELLO

)

;

console.

log

(

"Capitalize: "

CapitalizedHello

)

;

console.

log

(

"Uncapitalize: "

UncapitalizedHello

)

;

Running result:

Uppercase: HELLO

Lowercase: hello

Capitalize: Hello

Uncapitalize: hello

Application scenarios:These utility types are very useful in scenarios that require a consistent format, such as event names and method names.


Event type

Template literal types can be used to precisely define the types of event names.

Example

// Build an event name type

// on${Capitalize} Generate strings starting with "on" and with the first letter capitalized

type EventName

=

`on$

{

Capitalize

<

string

}

`

;

// handle${Capitalize} Generate strings starting with "handle" and with the first letter capitalized

type Handler

=

`handle$

{

Capitalize

<

string

}

`

;

// Only strings matching the format can be assigned

var

clickEvent

:

EventName

=

"onClick"

;

var

focusEvent

:

EventName

=

"onFocus"

;

var

handler

:

Handler

=

"handleSubmit"

;

console.

log

(

"Event: "

clickEvent

)

;

console.

log

(

"Handler: "

handler

)

;

Running result:

事件: onClick

处理器: handleSubmit

Advantages:After using template literal types, incorrect formats like "onclick" (lowercase) will be rejected by TypeScript.


Path Types

Template literal types can be used to precisely define the types of API paths.

Example

// Define an HTTP method type

type HttpMethod

=

"get"

|

"post"

|

"put"

|

"delete"

;

// Define the path format

type ApiEndpoint

=

`

/

$

{

string

}

`

;

 

// A string starting with a slash

// Combine into a complete API path type

type ApiPath

=

`$

{

HttpMethod

}

$

{

ApiEndpoint

}

`

;

// Only paths matching the format can be assigned

var

getUsers

:

ApiPath

=

"/get/users"

;

var

createUser

:

ApiPath

=

"/post/users"

;

console.

log

(

"Path: "

getUsers

)

;

console.

log

(

"Path: "

createUser

)

;

Running result:

路径: /get/users

路径: /post/users

Type safety:A path like "/users" (without a method prefix) will cause a TypeScript error.


Complex example

Template literal types can combine multiple union types to generate all possible combinations.

Example

// A template type with a number

// ${number} matches any number

type Row

=

`row$

{

number

}

`

;

type Row10

=

Row

;

 

// row0, row1, row2... up to row9...

// Combine multiple types

type Variant

=

"primary"

|

"secondary"

;

type Size

=

"sm"

|

"md"

|

"lg"

;

// This generates 6 combinations: btn-primary-sm, btn-primary-md, btn-primary-lg...

type ClassName

=

`btn

$

{

Variant

}

$

{

Size

}

`

;

// Only one of the 6 generated combinations can be assigned

var

className

:

ClassName

=

"btn-primary-md"

;

console.

log

(

"Class name: "

className

)

;

Running result:

类名: btn-primary-md

Combination explosion:Template literal types automatically expand all combinations. If a union type has many options, the generated type can become very large.


Custom Utility Types

You can create your own template literal utility types.

Example

// A utility type that adds a prefix

// T is any string, P is the prefix to add

type Prefix

<

T

extends

string

,

P

extends

string

=

`$

{

P

}

$

{

Capitalize

<

T

}

`

;

// A utility type that adds a suffix

// T is any string, S is the suffix to add

type Suffix

<

T

extends

string

,

S

extends

string

=

`$

{

Capitalize

<

T

}

$

{

S

}

`

;

// Use a custom utility type

type HandlerName

=

Prefix

<

"click"

,

"on"

;

type ButtonId

=

Suffix

<

"submit"

,

"Btn"

;

var

handler

:

HandlerName

=

"onClick"

;

var

id

:

ButtonId

=

"SubmitBtn"

;

console.

log

(

"Handler: "

handler

)

;

console.

log

(

"ID: "

id

)

;

Running result:

处理器: onClick

ID: SubmitBtn

Generic templates:Template literal types can be combined with generics to create reusable utility types.


Notes

Best practices:Using template literal types to handle strings with fixed formats such as event names, paths, and class names can provide better type safety.


Summary

Template literal types are part of TypeScript's powerful type system.

Note:In scenarios that require formatted strings, prefer template literal types to obtain compile-time type checking.