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

TypeScript Literal Types

TypeScript Literal Types

Literal types are a feature in TypeScript that represent specific values rather than general types.

They allow us to restrict a variable's type to a specific value rather than a broad type such as string or number.

This provides more precise type control and makes code more type-safe.


Literal Type Examples General type var direction: string; can be assigned any string "up", "down", "abc"... Literal type var direction: "up" | "down" | "left" | "right" can only be assigned one of these four values Type Safety When assigning an invalid value Compilation error! direction = "upup" Kinds of Literal Types String Literals "up" | "down" | "left" Restrict to a specific string Numeric literals 1 | 2 | 3 | 100 | 200 Restrict to a specific number Boolean literals true | false true or false Template literals `on${string}` Generate dynamically

Why Literal Types Are Needed

In TypeScript, default types such as string and number are too broad.

Sometimes we need more precise type control. For example, a variable may only take a few specific values.

Literal types were created precisely to solve this kind of problem.

Concept explanation:A literal type is a specific value of a general type (string, number). For example, "up" Is string is a subtype of it, and only specific strings can be assigned to it.


String Literal Types

String literal types restrict a variable's value to a specific string.

This is very useful when you need to restrict a variable to certain fixed values.

Example

// Define a string literal type

// direction can only be one of four specific values

var

direction

:

"up"

|

"down"

|

"left"

|

"right"

;

// Correct: assign a value from the literal type

direction

=

"up"

;

// Error: assign a value not in the list

// direction = "upup"; // compilation error!

console.

log

(

"Direction: "

direction

)

;

// Use a type alias to create a reusable literal type

// Define a status type: can only be one of three fixed values

type Status

=

"pending"

|

"active"

|

"completed"

;

// use type aliases

var

currentStatus

:

Status

=

"active"

;

console.

log

(

"Status: "

currentStatus

)

;

Running result:

方向: up

状态: active

Application scenarios:String literals are often used to define enum values, status codes, configuration options, and other scenarios that need to be restricted to specific values.


Numeric Literal Types

Numeric literal types restrict a variable's value to a specific number.

This is very useful when you need to use specific numeric values (such as status codes or error codes).

Example

// Define a numeric literal type

// code can only be one of three specific values

var

code

:

200

|

404

|

500

;

// Correct: assign 200

code

=

200

;

// Error: assign a value not in the list

// code = 301; // compilation error!

console.

log

(

"Status code: "

code

)

;

// Use numeric literals to simulate an enum

// Define the days of a week

type Weekday

=

1

|

2

|

3

|

4

|

5

|

6

|

7

;

// Can only assign numbers between 1 and 7

var

today

:

Weekday

=

1

;

console.

log

(

"Today is weekday: "

today

)

;

Explanation:Numeric literals can replace simple enums, especially when only a few fixed numeric values are needed.


Boolean Literal Types

Boolean literal types restrict a variable's value to true or false.

In fact, the boolean type in TypeScript is just an alias for true | false.

Example

// Define a boolean literal type

// isActive can only be true or false

var

isActive

:

true

|

false

;

// Assign true

isActive

=

true

;

// In fact, boolean is a union type of true | false

// So these two forms are equivalent

var

flag

:

boolean

=

true

;

console.

log

(

"Is active: "

isActive

)

;

Tip:Although boolean alone is sufficient, you can use true or false as a type when you need to clearly distinguish the two.


Object Literal Types

Object literal types can define the structure of an object, and you can use the readonly modifier to make properties read-only.

This is very useful when you need to create immutable objects.

Example

// Define an object literal type

// Specify the structure of the object and the types of its properties

type Point

=

{

   

// The x coordinate of the point

    x

:

number

;

   

// The y coordinate of the point

    y

:

number

;

}

;

// Use the object literal type

var

p

:

Point

=

{

x

:

10

,

y

:

20

}

;

console.

log

(

"Point: "

JSON.

stringify

(

p

)

)

;

// Define a read-only object type

// Use the readonly modifier to make properties read-only

type ReadonlyPoint

=

{

   

// Read-only x coordinate

    readonly x

:

number

;

   

// Read-only y coordinate

    readonly y

:

number

;

}

;

// Use the read-only object type

var

rp

:

ReadonlyPoint

=

{

x

:

1

,

y

:

2

}

;

// Trying to modify a read-only property will cause an error

// rp.x = 3; // compilation error: read-only properties cannot be modified

console.

log

(

"Read-only point: "

JSON.

stringify

(

rp

)

)

;

Running result:

点: {"x":10,"y":20}

只读点: {"x":1,"y":2}

Application scenarios:Read-only objects are often used to define configuration objects, constant objects, and other data that should not be modified.


Literal Types and Type Inference

TypeScript automatically infers literal types based on how a variable is declared.

Variables declared with const are inferred as specific literal types rather than broad types.

Example

// Declare and assign with var

// TypeScript will infer a broad type

var

name

=

"Alice"

;

   

// Type: string (because var can be reassigned)

var

age

=

25

;

         

// Type: number

var

enabled

=

true

;

   

// Type: boolean

console.

log

(

"Name: "

name

", Age: "

age

", Enabled: "

enabled

)

;

// Use as const to create deeply read-only literals

// The array becomes a read-only tuple, with values as literal types

var

colors

=

[

"red"

,

"green"

,

"blue"

]

as

const

;

// The type of colors becomes:

// readonly ["red", "green", "blue"]

// Access array elements

console.

log

(

"Colors: "

colors

[

0

]

)

;

// Trying to modify will cause an error

// colors[0] = "yellow"; // compilation error: read-only

Explanation:as const infers the type as the most specific literal type and adds the readonly modifier.


Template Literal Types

Template literal types use the syntax of JavaScript template strings to create new types.

They allow us to generate string types dynamically.

Example

// Define event names using template literal types

// on${string} represents any string starting with "on"

type EventName

=

`on$

{

string

}

`

;

// Define handler names using template literal types

// Capitalize uppercases the first letter of a string

type Handler

=

`handle$

{

Capitalize

<

string

}

`

;

// Use template literal types

var

event

:

EventName

=

"onClick"

;

var

handler

:

Handler

=

"handleSubmit"

;

console.

log

(

"Event: "

event

)

;

console.

log

(

"Handler: "

handler

)

;

// Error: does not match the template format

// var e: EventName = "click"; // compilation error: does not start with "on"

Running result:

事件: onClick

处理器: handleSubmit

Built-in utility types:Template literal types can be used together with built-in utility types such as Uppercase, Lowercase, Capitalize, and Uncapitalize.


Practical Application: Redux Action

Literal types have a wide range of applications in real development.

The following shows how to use literal types to implement Redux-style actions.

Example

// Define Redux-style Action types

// Use union types to define different kinds of Action

type Action

=

   

// Action of the increment type, with a numeric payload

   

|

{

type

:

"increment"

;

payload

:

number

}

   

// Action of the decrement type, with a numeric payload

   

|

{

type

:

"decrement"

;

payload

:

number

}

   

// Action of the reset type, with no payload

   

|

{

type

:

"reset"

}

;

// A reducer function that uses action

function

reducer

(

action

:

Action

)

:

void

{

   

// TypeScript automatically infers the specific type of action from the value of action.type

   

switch

(

action.

type

)

{

       

case

"increment"

:

           

// In this branch, action is inferred as { type: "increment"; payload: number }

            console.

log

(

"Increment: "

action.

payload

)

;

           

break

;

       

case

"decrement"

:

           

// In this branch, action is inferred as { type: "decrement"; payload: number }

            console.

log

(

"Decrement: "

action.

payload

)

;

           

break

;

       

case

"reset"

:

           

// In this branch, action is inferred as { type: "reset" }

            console.

log

(

"Reset"

)

;

           

break

;

   

}

}

// Dispatch different types of Action

reducer

(

{

type

:

"increment"

,

payload

:

5

}

)

;

reducer

(

{

type

:

"reset"

}

)

;

Running result:

增加: 5

重置

Discriminated union:This pattern is called a "discriminated union," a best practice in TypeScript for handling multiple related types.


Notes

Best practices:When you need to restrict a variable to specific values, prefer literal types over enums.


Summary

Literal types are an important feature of TypeScript for achieving precise type control.

Advanced:Literal types combined with the discriminated union pattern can achieve powerful type safety.