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

TypeScript Utility Types

TypeScript Utility Types

Utility Types are a series of advanced types built into TypeScript.

They help developers quickly create and transform types, improving code reusability and type safety.

Utility types are essentially generic types, implemented through mapped types and conditional types.


TypeScript Utility Types Original type interface User { id: number; name: string; email: string; } Tool Type Partial - All optional Required - All required Readonly - All readonly Pick - Select properties Omit - Exclude properties Result type type Result = { id?: number; name?: string; email?: string; } Common utility types Partial All properties optional { a?: T } Required All properties required { -? } Readonly All properties readonly { readonly } Pick Select specified properties { pick } Record Construct an object type Omit Exclude specified properties

Why utility types are needed

In real TypeScript development, we often need to create new types based on existing ones.

Creating these types manually is not only tedious but also error-prone.

Utility types provide a declarative way to transform and create types, greatly improving development efficiency.

Concept explanation:Utility types are a set of predefined generic types in TypeScript. They use mapped types and conditional types to implement type transformation and generation.


Partial - Optional properties

Partial makes all properties of type T optional.

This is very useful when creating partial update objects or handling form data.

Example

// Define a user interface with required properties

interface

User

{

   

// The user ID

    id

:

number

;

   

// Username

    name

:

string

;

   

// User email

    email

:

string

;

}

// Partial: make all properties optional

// All properties of the converted type are optional

type PartialUser

=

Partial

<

User

;

// Use the PartialUser type

// You can provide only some properties, not all

var

user

:

PartialUser

=

{

name

:

"Alice"

}

;

console.

log

(

"Partial user: "

JSON.

stringify

(

user

)

)

;

Running result:

部分用户: {"name":"Alice"}

Application scenarios:Partial is commonly used to update object data. For example, when updating only part of a user's information, you don't need to pass a complete user object.


Required - Required properties

Required is the opposite of Partial, making all optional properties required.

Use it when you need to ensure an object contains all properties.

Example

// Define a configuration interface whose properties are all optional

interface

Config

{

   

// Server address

    host

?:

string

;

   

// Port number

    port

?:

number

;

}

// Required: make all optional properties required

// All properties of the converted type are required

type RequiredConfig

=

Required

<

Config

;

// Use the RequiredConfig type

// All properties must be provided

var

config

:

RequiredConfig

=

{

host

:

"localhost"

,

port

:

8080

}

;

console.

log

(

"Config: "

JSON.

stringify

(

config

)

)

;

Running result:

配置: {"host":"localhost","port":8080}

Explanation:Required not only removes the optional property (?) but also the readonly modifier.


Readonly - Readonly properties

Readonly makes all properties readonly.

Very useful when creating objects that should not be modified after creation.

Example

// Define a user interface

interface

User

{

   

// Username

    name

:

string

;

   

// User age

    age

:

number

;

}

// Readonly: make all properties readonly

// No properties of the converted type can be modified

type ReadonlyUser

=

Readonly

<

User

;

// Create a readonly user object

var

user

:

ReadonlyUser

=

{

name

:

"Alice"

,

age

:

25

}

;

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

// user.name = "Bob"; // Error: readonly property cannot be modified

console.

log

(

"Readonly user: "

JSON.

stringify

(

user

)

)

;

Application scenarios:Readonly is commonly used to define configuration objects, enum value mappings, and other data that should not be modified.


Pick - Select properties

Pick selects specified properties K from type T to form a new type.

Use it when you only need part of a type's properties.

Example

// Define a complete user interface

interface

User

{

   

// The user ID

    id

:

number

;

   

// Username

    name

:

string

;

   

// User email

    email

:

string

;

   

// User password

    password

:

string

;

}

// Pick: select specified properties to form a new type

// Select the id and name properties from User

type UserBasicInfo

=

Pick

<

User

,

"id"

|

"name"

;

// Use the selected type

var

user

:

UserBasicInfo

=

{

id

:

1

,

name

:

"Alice"

}

;

console.

log

(

"Basic user info: "

JSON.

stringify

(

user

)

)

;

Running result:

用户基本信息: {"id":1,"name":"Alice"}

Comparison:Pick and Partial can be combined to create a type containing only some optional properties.


Omit - Exclude properties

Omit excludes specified properties K from type T, returning a new type composed of the remaining properties.

The opposite of Pick, used to remove unwanted properties.

Example

// Define a complete user interface

interface

User

{

   

// The user ID

    id

:

number

;

   

// Username

    name

:

string

;

   

// User email

    email

:

string

;

   

// User password

    password

:

string

;

}

// Omit: exclude specified properties

// Exclude the password property from User

type UserWithoutPassword

=

Omit

<

User

,

"password"

;

// Use the excluded type

var

user

:

UserWithoutPassword

=

{

id

:

1

,

name

:

"Alice"

,

email

:

"a@b.com"

}

;

console.

log

(

"User without password: "

JSON.

stringify

(

user

)

)

;

Running result:

无密码用户: {"id":1,"name":"Alice","email":"a@b.com"}

Tip:Omit is the reverse operation of Pick. Use Omit when you need to exclude a few properties, and Pick when you need to select a few properties.


Record - Construct an object type

Record constructs an object type with keys of type K and values of type T.

Commonly used to create key-value mappings, dictionary types, etc.

Example

// Define a role type

type Role

=

"admin"

|

"user"

|

"guest"

;

// Record: construct an object type

// Keys are of type Role, values are of string array type

type RolePermissions

=

Record

<

Role

,

string

[

]

;

// Use Record to create a permissions mapping

var

permissions

:

RolePermissions

=

{

   

// Administrators have all permissions

    admin

:

[

"read"

,

"write"

,

"delete"

]

,

   

// Regular users have read and write permissions

    user

:

[

"read"

,

"write"

]

,

   

// Guests have read-only permissions

    guest

:

[

"read"

]

}

;

console.

log

(

"Admin permissions: "

permissions.

admin

)

;

console.

log

(

"Guest permissions: "

permissions.

guest

)

;

Running result:

管理员权限: read,write,delete

访客权限: read

Application scenarios:Record is commonly used in scenarios requiring fast value lookup by key, such as configuration mappings, state mappings, and permission mappings.


Exclude - Exclude types

Exclude removes from type T the types that can be assigned to type U.

Mainly used with union types to exclude specific type members.

Example

// Define a union type containing a, b, c, d

type T

=

"a"

|

"b"

|

"c"

|

"d"

;

// Exclude: exclude specified types from T

// Exclude "a", "b", "c", keeping only "d"

type NonABC

=

Exclude

<

T

,

"a"

|

"b"

|

"c"

;

// Using the excluded type, only "d" can be assigned

var

value

:

NonABC

=

"d"

;

console.

log

(

"Value: "

value

)

;

Running result:

值: d

Explanation:The principle of Exclude: if a type in T can be assigned to U, it is removed from T.


Extract - Extract types

Extract is the opposite of Exclude; it extracts from type T the types that can be assigned to type U.

Used to filter specific members from a union type.

Example

// Define a mixed union type containing strings and numbers

type T

=

"a"

|

"b"

|

"c"

|

1

|

2

|

3

;

// Extract: extract specified types from T

// Extract all string types: "a", "b", "c"

type Letters

=

Extract

<

T

,

string

;

// Use the extracted type

var

letter

:

Letters

=

"a"

;

console.

log

(

"Letters: "

letter

)

;

Running result:

字母: a

Comparison:Extract and Exclude are complementary. Extract(T, U) is equivalent to Exclude(T, Exclude)。


NonNullable - Exclude null values

NonNullable removes null and undefined from type T.

Use it when you need to ensure a type does not contain null values.

Example

// Define a mixed type containing string, null, undefined, number

type T

=

string

|

null

|

undefined

|

number

;

// NonNullable: exclude null and undefined

// Only string and number remain after conversion

type NotNull

=

NonNullable

<

T

;

// Use the non-nullable type

var

value

:

NotNull

=

"hello"

;

value

=

42

;

// Trying to assign null will cause an error

// value = null; // Error: cannot assign null

console.

log

(

"Value: "

value

)

;

Explanation:NonNullable equivalent to Exclude。


ReturnType - Get the return type

ReturnType obtains the return type of function type T.

Commonly used to extract the return type from an existing function.

Example

// Define a function that gets a user

function

getUser

(

)

{

   

return

{

name

:

"Alice"

,

age

:

25

}

;

}

// Define a function that gets configuration

function

getConfig

(

)

{

   

return

{

host

:

"localhost"

,

port

:

8080

}

;

}

// ReturnType: get the return type of a function

// Extract the return type of the getUser function

type UserType

=

ReturnType

<

typeof

getUser

;

// Extract the return type of the getConfig function

type ConfigType

=

ReturnType

<

typeof

getConfig

;

// Create an object using the extracted return type

var

user

:

UserType

=

{

name

:

"Bob"

,

age

:

30

}

;

var

config

:

ConfigType

=

{

host

:

"example.com"

,

port

:

3000

}

;

console.

log

(

"User: "

JSON.

stringify

(

user

)

)

;

console.

log

(

"Config: "

JSON.

stringify

(

config

)

)

;

Running result:

用户: {"name":"Bob","age":30}

配置: {"host":"example.com","port":3000}

Tip:ReturnType The T in it must be a function type. You can use typeof to obtain a function's type.


Notes

Advanced:If the built-in utility types do not meet your needs, you can implement custom utility types by referring to the TypeScript source code.


Summary

TypeScript utility types are an important part of the type system.

Best practices:Making good use of utility types can make code more type-safe, reduce duplicate type definitions, and improve code maintainability.