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

TypeScript type Aliases

TypeScript type Aliases

A type alias (Type Alias) is used to create an alias for an existing type, making the code more concise and readable.

With type aliases, you can define a short name for a complex type, improving code maintainability.


How type Aliases Work Original complex type type User = { name: string; age: number; email: string; } define type alias type UserID = User; // or type ID = string | number; Use The code uses var id: UserID; var uid: ID; Application Scenarios of type Aliases Basic type aliases Union type aliases Function type aliases Generic type aliases

Why type Aliases Are Needed

When the same complex type is used multiple times in code, writing out the full type each time is verbose.

A type alias can define a concise name for a complex type, making the code easier to read and maintain.

Type aliases are especially useful when working with complex types such as union types, function types, and tuples.

Concept explanation:Using type Aliases type Defined with the type keyword; it simply gives an existing type a new name and does not create a new type.


Basic Usage

Use the type keyword to define an alias for a type.

Example

// Type alias: define an alias for a union type

// ID can be a string or a number

type ID

=

string

|

number

;

// Type alias: define an alias for an object type

// Point represents a coordinate point

type Point

=

{

x

:

number

;

y

:

number

}

;

// use type aliases

var

userId

:

ID

=

"123"

;

var

productId

:

ID

=

456

;

// Use the Point type alias

var

point

:

Point

=

{

x

:

10

,

y

:

20

}

;

console.

log

(

"User ID: "

userId

)

;

console.

log

(

"Product ID: "

productId

)

;

console.

log

(

"Coordinates: "

JSON.

stringify

(

point

)

)

;

Running result:

用户ID: 123

产品ID: 456

坐标: {"x":10,"y":20}

Explanation:A type alias simply gives a type a new name; it produces no actual code after compilation and is used entirely for type checking during development.


Interfaces vs type aliases

Type aliases and interfaces are very similar; both can be used to define object types, but there are some subtle differences.

Example

// Use a type alias to define an object type

// type can define any type, not just objects

type PersonType

=

{

    name

:

string

;

    age

:

number

;

}

;

// Use an interface to define an object type

// Interfaces support declaration merging and can be implemented by classes

interface

PersonInterface

{

    name

:

string

;

    age

:

number

;

}

// Both can be used to declare variable types

var

person1

:

PersonType

=

{

name

:

"Alice"

,

age

:

25

}

;

var

person2

:

PersonInterface

=

{

name

:

"Bob"

,

age

:

30

}

;

console.

log

(

"PersonType: "

JSON.

stringify

(

person1

)

)

;

console.

log

(

"PersonInterface: "

JSON.

stringify

(

person2

)

)

;

Difference:type can define any type (union types, tuples, function types, etc.), while interfaces are mainly used to define object types. Interfaces support declaration merging, but type does not.


Type Aliases and Union Types

Type aliases are ideal for defining union types, making the code clearer.

Example

// Union type alias: define the possible values of a state

// Status can only be one of these three string literals

type Status

=

"pending"

|

"success"

|

"error"

;

// Union type alias: define multiple possible return types

// Result can be a string, number, or boolean

type Result

=

string

|

number

|

boolean

;

// Use the union type alias

function

getStatus

(

status

:

Status

)

:

void

{

    console.

log

(

"Status: "

status

)

;

}

getStatus

(

"success"

)

;

getStatus

(

"error"

)

;

// Use the Result type

var

result

:

Result

=

"hello"

;

result

=

42

;

console.

log

(

"Result: "

result

)

;

Running result:

状态: success

状态: error

结果: 42

Application scenarios:Union type aliases are commonly used to define status codes, error types, API return values, and similar scenarios.


Type Aliases and Tuples

Type aliases can also be used to define tuple types.

Example

// Tuple type alias: define a coordinate

// Coordinate is a tuple containing two numbers

type Coordinate

=

[

number

,

number

]

;

// Tuple type alias: define a name and age

// NameAge is a tuple of a string and a number

type NameAge

=

[

string

,

number

]

;

// Use the tuple type alias

var

coord

:

Coordinate

=

[

10

,

20

]

;

var

person

:

NameAge

=

[

"Alice"

,

25

]

;

console.

log

(

"Coordinates: "

coord

)

;

console.

log

(

"Information: "

person

[

0

]

", "

person

[

1

]

)

;

Explanation:Tuple type aliases make the use of tuples clearer, avoiding the need to write out the full tuple type each time.


Type Aliases and Functions

Type aliases can simplify function type declarations.

Example

// Function type alias: define a callback function type

// Callback takes a string parameter and returns void

type Callback

=

(

result

:

string

)

=>

void

;

// Function type alias: define a math operation function type

// MathOperation takes two number parameters and returns a number

type MathOperation

=

(

a

:

number

,

b

:

number

)

=>

number

;

// Use the function type alias

var

add

:

MathOperation

=

function

(

a

,

b

)

{

return

a

b

;

}

;

var

multiply

:

MathOperation

=

function

(

a

,

b

)

{

return

a

b

;

}

;

console.

log

(

"Addition: "

add

(

2

,

3

)

)

;

console.

log

(

"Multiplication: "

multiply

(

4

,

5

)

)

;

Running result:

加法: 5

乘法: 20

Advantages:Function type aliases make function type declarations more concise, especially when the same function signature is used multiple times.


Type Aliases and Generics

Type aliases can be used with generics to create reusable type definitions.

Example

// Generic type alias: define a result type

// Result is a generic type, where T is the data type on success

type Result

<

T

=

{

success

:

boolean

;

data

?:

T

;

error

?:

string

}

;

// Generic type alias: define a key-value pair type

// Pair has two type parameters

type Pair

<

K

,

V

=

{

key

:

K

;

value

:

V

}

;

// Use the generic type alias

var

result

:

Result

<

string

=

{

success

:

true

,

data

:

"Hello"

}

;

var

pair

:

Pair

<

string

,

number

=

{

key

:

"age"

,

value

:

25

}

;

console.

log

(

"Result: "

JSON.

stringify

(

result

)

)

;

console.

log

(

"Key-value pair: "

JSON.

stringify

(

pair

)

)

;

Running result:

结果: {"success":true,"data":"Hello"}

键值对: {"key":"age","value":25}

Advantages of generics:Generic type aliases can adapt to different data types, improving code reusability.


Type Aliases and Mapped Types

Type aliases can be combined with mapped types to create powerful type transformations.

Example

// Mapped type: make all properties readonly

// Readonly Traverse all properties of T and add readonly

type Readonly

<

T

=

{

readonly

[

P

in

keyof T

]

:

T

[

P

]

}

;

// Mapped type: make all properties optional

// Partial Traverse all properties of T and add ?

type Partial

<

T

=

{

[

P

in

keyof T

]

?:

T

[

P

]

}

;

// Define a user interface

interface

User

{

    name

:

string

;

    age

:

number

;

}

// Use a mapped type alias

var

readonlyUser

:

Readonly

<

User

=

{

name

:

"Alice"

,

age

:

25

}

;

// readonlyUser.name = "Bob"; // Error: a read-only property cannot be modified

var

partialUser

:

Partial

<

User

=

{

name

:

"Bob"

}

;

console.

log

(

"Readonly user: "

JSON.

stringify

(

readonlyUser

)

)

;

console.

log

(

"Partial user: "

JSON.

stringify

(

partialUser

)

)

;

Tip:Mapped types are a very powerful feature of TypeScript that can create new type variations based on existing types.


Notes

Best practices:Use type aliases when a type needs to be reused or when the type name is too long. For simple object types, you can choose type or interface according to your team's conventions.


Summary

type aliases are a very useful feature in TypeScript.

Note:Using type aliases reasonably can make code clearer, but do not overuse them; keeping code concise and readable is most important.